Search code examples
androidandroid-fragmentsmvvmandroidxandroid-jetpack

MVVM Single Activity app return to a nested fragment with Navigation component after leaving app or launching intent


I am trying to return to a specific fragment after pressing the home button, sharing data with another app or switching activities.

Fragments in bottomNav:

A B C D

Fragments that are shared around the app and can be nested or navigated to from the bottomNav fragments:

E F G

Intended behaviour

User navigation stack:

A -> E

Presses home button and reopens app, stack remains the same.

A -> E

Actual Behaviour

User navigation stack:

A -> E

Presses home button and reopens app, brought back to first fragment

A

I tried to restore the navigation state by passing a bundle from navController.saveState() to a viewmodel during the Main Activity onPause method and restoring it with navController.restoreState() onResume to no avail. Is this not capable with the navigation component?


Solution

  • What you are looking for is called Multiple Backstack. Every Fragment in android maintains its own stack. So if you navigate to another Fragment in the ParentFragment, your ParentFragment will add the childFragment in its stack. In your case, your ParentFragment is A and childFragment is E.

    However, NavigationComponent has no vanilla support for Multiple Backstack. Ian Lake, the creator of NavigationComponent library is working on this issue since NavigationComponent was launched, and still haven't delivered on it. This doesn't mean he is not working on it, it simply means (as stated by Ian himself) that its harder to achieve because of Fragments API.

    Coming back to your question, if you really want to implement MultipleBackstack then you can follow this project which pretty much anyone who wants MultipleBackstack with NavigationComponent first refers to. There is also a google sample that shows how to achieve this behavior.