Search code examples
androidandroid-architecture-componentsandroid-jetpackandroid-architecture-navigation

Disable adding fragment to backstack in Navigation Architecture Component


Suppose i have 4 fragments: A, B, C, X, and I can navigate between them in this way:

... -> A -> C -> X    and ... -> B -> C -> X

But when I'm in fragment X call mNavController.navigateUp() I want skip fragment C and go to fragment A or B. What I need to do?

UPD: I need solution only for Navigation Architecture Component https://developer.android.com/topic/libraries/architecture/navigation/ Thanks!


Solution

  • Given R.id.fragmentC is the name of C destination, from X destination, you can do the following:

    NavController controller = Navigation.findNavController(view);
    controller.popBackStack(R.id.fragmentC, true);
    

    This should pop all destinations off the stack until before C, and leave either A or B on top of the stack.