20

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!

Francis
  • 6,788
  • 5
  • 47
  • 64
igor_rb
  • 1,821
  • 1
  • 19
  • 34

3 Answers3

30

Alternatively you could use app:popUpTo and app:popUpToInclusive attributes in navigation xml resource to cleanup back stack automatically when perform certain transactions, so back / up button will bring your user to the root fragment.

<fragment
    android:id="@+id/fragment1"
    android:name="com.package.Fragment1"
    android:label="Fragment 1">

    <action
        android:id="@+id/action_fragment1_to_fragment2"
        app:destination="@id/fragment2"
        app:popUpTo="@id/fragment1"
        app:popUpToInclusive="true / false" />

</fragment>
Viacheslav
  • 5,443
  • 1
  • 29
  • 36
24

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.

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
bentesha
  • 898
  • 9
  • 14
5

As mentioned by @bentesha this works in this way that it will pop fragments until fragmentC inclusively.

You can also achieve this as below:

NavController controller = Navigation.findNavController(view);
controller.popBackStack(R.id.fragmentA, false);

OR

NavController controller = Navigation.findNavController(view);
controller.popBackStack(R.id.fragmentB, false);

And this will pop up to fragmentA/fragmentB exclusively, I think it's most descriptive way for yourself and for others to understand.

Muhammad Maqsood
  • 1,622
  • 19
  • 25
  • What if there were dynamically changing locations the user could navigate in from? (for example, there are destinations A, B, X, Y, Z. How could we identify which one was navigated from in order to navigate back to it dynamically? – Thomas Oct 09 '20 at 12:07