Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Jetpack Navigation nested tab backward navigation strange behaviour

So I'm trying Jetpack navigation component with BottomNavigationView. I created two layer of BottomNavigationView, and the structure looks like this:

  • MainActivity (with nav_host_fragment, navigation_graph, bottom_navigation)
    • FragmentA
    • FragmentB
    • FragmentC (with nested_nav_host_fragment, nested_navigation_graph, nested_bottom_navigation)
      • FragmentCA
      • FragmentCB
      • FragmentCC

I have no problem navigating forward, but I couldn't navigate backward properly. For example, when I navigation from A -> B -> C, and in C navigate CA -> CB -> CC, then clicking back button or calling navControler back, it should go from CC -> CB -> CA -> B -> A, but it straightly went to A instead.

The minimum demo project can be found here, hope someone can help, thanks.

like image 930
Joshua Lin Avatar asked Sep 09 '26 13:09

Joshua Lin


1 Answers

By default, Fragments do not pop anything added to the back stack of child fragments.

To get the system back button to pop child Fragments of your Fragment C, you must specifically opt into that behavior by calling setPrimaryNavigationFragment().

This can be done anywhere in your Fragment after your Fragment is attached. For example, you can update your FragmentC to do it in 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()
}

This is actually the same technique that the app:defaultNavHost="true" attribute on NavHostFragment is using under the hood.

like image 193
ianhanniballake Avatar answered Sep 11 '26 06:09

ianhanniballake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!