Android Jetpack Navigation嵌套选项卡向后导航的奇怪行为

use*_*482 3 android android-architecture-navigation

所以我正在尝试使用BottomNavigationView的Jetpack导航组件。我创建了两层BottomNavigationView,其结构如下所示:

  • MainActivity(带有nav_host_fragment,navigation_graph,bottom_navigation)
    • 片段A
    • 片段B
    • FragmentC(带有nested_nav_host_fragment,nested_navigation_graph,nested_bottom_navigation)
      • 片段CA
      • 片段CB
      • 片段CC

向前导航没有问题,但无法正确向后导航。例如,当我从A-> B-> C导航,并在C中导航CA-> CB-> CC,然后单击“后退”按钮或调用navControler返回时,它应从CC-> CB-> CA-> B -> A,但直接转到A。

最小的演示项目可以在这里找到,希望有人可以帮助,谢谢。

ian*_*ake 5

默认情况下,片段不会弹出添加到子片段后排堆栈中的任何内容。

要使系统返回按钮弹出片段C的子片段,必须通过调用setPrimaryNavigationFragment()专门选择加入该行为。

片段连接后,可以在片段中的任何位置进行此操作。例如,您可以更新FragmentC以在中进行操作onActivityCreated()

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    NavigationUI.setupWithNavController(nested_bottom_navigation,
            activity?.findNavController(R.id.nested_nav_host_fragment)?:return)

    // This routes the system back button to this Fragment
    requireFragmentManager().beginTransaction()
            .setPrimaryNavigationFragment(this)
            .commit()
}
Run Code Online (Sandbox Code Playgroud)

这实际上与app:defaultNavHost="true"属性在NavHostFragment后台使用的技术相同。