Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear back stack of Fragments in Navigation Component?

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.

like image 214
c-an Avatar asked Jun 17 '19 08:06

c-an


1 Answers

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.

like image 184
Grigoriym Avatar answered Sep 22 '22 01:09

Grigoriym