OBS: Though still no first class support (as of writing this), Google has now updated their samples with an example of how they think this should be solved: https://github.com/googlesamples/android-architecture-components/tree/master/NavigationAdvancedSample
The Android Codelab for Navigation does a good job describing how to use the architecture component Navigation together with a BottomNavigationView
. But let's say I have 2 tabs in the BottomNavigationView
, Tab1 and Tab2. And let's say that in Tab1 you navigate through the fragments Frag1 --> Frag2. Now, whenever I go to Tab2, and then back to Tab1, the fragment back stack of Frag1,2 is gone, and replaced with the starting point Frag1 again.
What do I have to do in an app so that a BottomNavigationView
together with Navigation keeps its back stack intact even though I change tabs? And, also keeping the back/up button behaviours in sync with the guidelines.
Previously I've done this with the use of ViewPager
and managing the back stack my selfe, but that doesn't feels like the right approach with the new Navigation.
Thanks in advance!
Edit:
There's a more elaborate answer here.
Use Up or Back button to go to a previous step of the order flow.
Multiple Back Stack Support With these extensions, the app keeps a separate NavHostFragment with its own back stack for each tab and swaps between them as the user switches from one tab to another.
NavController manages app navigation within a NavHost . Apps will generally obtain a controller directly from a host, or by using one of the utility methods on the Navigation class rather than create a controller directly. Navigation flows and destinations are determined by the navigation graph owned by the controller.
The major reason is you only use one NavHostFragment
to hold the whole back stack of the app.
So the solution is each tab should hold its own back stack.
FrameLayout
.NavHostFragment
and contains its own navigation graph in order to make each tab fragment having its own back stack.BottomNavigationView.OnNavigationItemSelectedListener
to BottomNavigtionView
to handle the visibility of each FrameLayout
.If you don't want to keep all the fragments in memory, you can use app:popUpTo
and app:popUpToInclusive="true"
to pop out the ones you don't want to keep.
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