So I'm trying Jetpack navigation component with BottomNavigationView. I created two layer of BottomNavigationView, and the structure looks like this:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With