igor_rb
igor_rb

Reputation: 1891

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!

Upvotes: 22

Views: 26898

Answers (3)

Viacheslav
Viacheslav

Reputation: 5593

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>

Upvotes: 33

bentesha
bentesha

Reputation: 948

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.

Upvotes: 24

Muhammad Maqsood
Muhammad Maqsood

Reputation: 1662

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.

Upvotes: 5

Related Questions