Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Jetpack Navigation proper back stack with BottomNavigationView

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.

like image 602
Algar Avatar asked Sep 02 '18 18:09

Algar


People also ask

How do I go back to previous fragment in navigation component?

Use Up or Back button to go to a previous step of the order flow.

What is multiple backstack?

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.

What is NavController in Android?

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.


1 Answers

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.

  • In your main layout, wrap each tab fragment with a FrameLayout.
  • Each tab fragment is a NavHostFragment and contains its own navigation graph in order to make each tab fragment having its own back stack.
  • Add a 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.

like image 85
jaychang0917 Avatar answered Nov 15 '22 19:11

jaychang0917