8

I tried with FragmentManager like this:

Navigation.findNavController(mView).popBackStack() 

And tried using FragmentManager.

val fm = activity!!.supportFragmentManager 

1.

fm.popBackStack() 

2.

fm.popBackStackImmediate() 

But They didn't work. I mean, It seems like they pop all the fragments.

I also tried applying these attributes in graph_nav.xml:

app:launchSingleTop="true" app:popUpToInclusive="true" 

I applied them in the A fragment and also B fragment.

I want to go to B fragment from A fragment. And I want to clear all the fragment stack before B fragment and just leave B fragment alone.

1 Answer 1

10

You need to add app:popUpToInclusive="true", app:launchSingleTop="true" and app:popUpTo="nav_graph_id" to the action tag in your nav_graph.xml.

<fragment android:id="@+id/firstFragment" android:name="com.example.ui.FirstFragment" android:label="First" tools:layout="@layout/fragment_first" > <action android:id="@+id/clearBackStack" app:destination="@id/secondFragment" app:launchSingleTop="true" app:popUpTo="@+id/nav_graph" app:popUpToInclusive="true" /></fragment> 

Then build the project (so that the directions file will be created), and write this:

findNavController().navigate(FirstFragmentDirections.clearBackStack()) 

Even though you have several nav_graphs, set the popUpTo's id of the main/home nav_graph, not the one where you write this action, e.g. your main nav_graph is "main_nav_graph.xml", and you write the above code in "some_other_nav_graph.xml", set the id of the main_nav_graph.xml.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't have nav_graph.id. Should I create <action> tag and put id in the root of navgraph?
If you have only one fragment and no action is there what will we do?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.