ViewPager 吞下 onBackPressed,因此无法导航 FragmentContainerView

ViewPager swallows onBackPressed so FragmentContainerView cannot be navigated

所以我有一个具有以下布局的应用程序

Activity -> ViewPager -> FragmentA -> FragmentContainerView -> FragmentB

FragmentContainerView 包含一个 NavHostFragment,它使用 nav_graph 显示 FragmentBFragmentB 中有一个按钮可以导航到 FragmentB 的新实例。所以导航图基本上只是一个片段,它本身有 link。

现在,如果我的 activity 中直接包含 FragmentContainerView,则效果很好。但是,如果我将 FragmentContainerView 放在 ViewPager 内的另一个片段中,后退按钮不再允许我导航 FragmentB 导航图。

我在 FragmentContainerView 上使用 app:defaultNavHost="true",但没有用。

知道我做错了什么吗?我能做些什么来解决它?

根据 Fragment Manager guide:

Consider the navigation structure as a series of layers, with the activity as the outermost layer, wrapping each layer of child fragments underneath. Each layer must have a single primary navigation fragment. When the Back event occurs, the innermost layer controls navigation behavior. Once the innermost layer has no more fragment transactions from which to pop back, control returns to the next layer out, and this process repeats until you reach the activity.

因此,当 app:defaultNavHost="true"FragmentA 内的 NavHostFragment 设置为其层(FragmentAchildFragmentManager 层)中的主要导航片段时, FragmentA 必须 被设置为主要导航片段,以便任何系统后退按钮事件完全进入 FragmentA

同一个页面提出了如何做到这一点:

To define the primary navigation fragment inside of a fragment transaction, call the setPrimaryNavigationFragment() method on the transaction, passing in the instance of the fragment whose childFragmentManager should have primary control.

虽然 ViewPager2 有 API 到 ,但 ViewPager1 没有这样的 API(您绝对应该移至 ViewPager2 的众多原因之一)。

作为 ViewPager1 中的解决方法,FragmentA 可以将自己设置为 onResume() 中的主要导航片段:

public fun onResume() {
    super.onResume()
    parentFragmentManager
        .beginTransaction()
        .setPrimaryNavigationFragment(this)
        .commit()
}