Search code examples
androidandroid-jetpackandroid-jetpack-navigation

Android Navigate Component navigate to sub graph


I hava two Fragment(OverviewFragment、PersonalFragment), and one sub graph(contains two Fragment :BucketsFragment and ObjectsFragment, BucketsFragment is start destination). They are bind to one BottomNavigateView.

Now, After navigate to the sub graph start destination(BucketsFragment), and continue to navigate to ObjectsFragment. Then navigate to OverviewFragment and finally return to the sub graph.

Now, I came to start destination(BucketsFragment), but actually what I want is ObjectsFragment. what should I do?

The whole process is shown here

I want to navigate to the sub graph that retains the previous state, instead of a new sub graph.


Solution

  • As per the material design guidelines for bottom navigation:

    On Android: the app navigates to a destination’s top-level screen. Any prior user interactions and temporary screen states are reset, such as scroll position, tab selection, and in-line search.

    So technically, this behavior is expected.

    When you're on the Resources tab and go to the ObjectsFragment, the back stack is

    DashBoardFragment -> BucketsFragment -> ObjectsFragment
    

    When you go back to the Overview tab, the back stack becomes

    DashBoardFragment
    

    And no state is saved for Fragments that aren't on the back stack. That's why when you reselect the Resources tab, it is recrated from scratch and you get back to

    DashBoardFragment -> BucketsFragment
    

    There's an existing issue for supporting multiple back stacks which aims to bring support for saving the state of each tab separately, allowing the behavior you wish. As per that issue, this requires significant changes to how Fragments work (since they are the one saving the state of Fragments) as well as integration into Navigation itself.

    That issue points out a temporary workaround, demonstrated in the NavigationAdvancedSample where each tab uses its own separate navigation graph and separate NavHostFragment, thus allowing each one to keep its own state independently from one another. This requires a bit different of a setup in the MainActivity and the help of a set of NavigationExtensions to get that working.

    It is expected that all of that functionality, once the multiple back stacks work is done, to be folded into the Navigation library itself.