I'm using Jetpack Navigation version 1.0.0-alpha04
with bottom navigation. It works but the navigation doesn't happen correctly. For example, if I have tab A and tab B and from tab A I go to Page C and from there I go to tab B and come back to tab A again, I will see root fragment in the tab A and not page C which does not what I expect.
I'm looking for a solution to have a different stack for each tab, so the state of each tab is reserved when I come back to it, Also I don't like to keep all this fragment in the memory since it has a bad effect on performance, Before jetpack navigation, I used this library https://github.com/ncapdevi/FragNav, That does exactly what, Now I'm looking for the same thing with jetpack navigation.
EDIT 2: 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 for now: https://github.com/googlesamples/android-architecture-components/tree/master/NavigationAdvancedSample
The major reason is you only use one
NavHostFragment
to hold the whole back stack of the app.The solution is that 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
toBottomNavigtionView
to handle the visibility of each FrameLayout.This also takes care of your "...I don't like to keep all this fragment in memory...", because a Navigation with
NavHostFragment
by default usesfragmentTransaction.replace()
, i.e. you will always only have as many fragments as you haveNavHostFragment
s. The rest is just in the back stack of your navigation graph.Edit: Google is working on a native implementation https://issuetracker.google.com/issues/80029773#comment25
More in detail
Let's say you have a
BottomNavigationView
with 2 menu choices,Dogs
andCats
.Then you need 2 navigation graphs, say
dog_navigation_graph.xml
andcat_navigation_graph.xml
.The
dog_navigation_graph
might look likeand the corresponding for
cat_navigation_graph
.In your
activity_main.xml
, add 2NavHostFragment
sand underneath add the corresponding for your cat
NavHostFragment
. On your cat frame layout, setandroid:visibility="invisible"
Now, in your
MainActivity
'sonCreateView
you canAll that
showHostView()
is doing is toggling the visibility of yourFrameLayout
s that are wrapping theNavHostFragment
s. So make sure to save them in some way, e.g. inonCreateView
Now it's easy to toggle which
hostViews
should be visible and invisible.