Reputation: 5984
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.
Upvotes: 12
Views: 5852
Reputation: 43
This is currently not supported in the new Navigation Architecture. I was also pretty bummed by this, as it is a very basic feature in today's apps, and a lot of the apps are now using the bottom navigation. There is a running thread, if you wanna keep an eye on it. They are saying they will come up with a long term solution for this, but for the shorter run, they are gonna give a sample on how to tackle this. https://issuetracker.google.com/issues/80029773#comment25
Upvotes: 1
Reputation: 1888
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.
Upvotes: 5