How to Clear Navigation Stack After Navigating to Another Fragment in Android

How to clear navigation Stack after navigating to another fragment in Android

First, add attributes app:popUpTo='your_nav_graph_id' and app:popUpToInclusive="true" to the action tag.

tools:layout="@layout/fragment_sign_in" >
app:popUpToInclusive="true" />

Second, navigate to the destination, using above action as parameter.


See the docs for more information.

NOTE: If you navigate using method navigate(@IdRes int resId), you won't get the desired result. Hence, I used method navigate(@NonNull NavDirections directions).

Navigation Component: How to clear back stack WHEN NAVIGATING FROM FRAGMENT TO ACTIVITY?

I got it working. The above example is working just as it should, the only catch is REMOVE the POPUPTO, POPUPTOINCLUSIVE and LAUNCHSINGLETOP attributes from the ACTION related to this Fragment-Activity transition EVEN IF THESE ATTRIBUTES HAVE VALUE "FALSE". If you just toggle them off using the design of navigation xml they will still be present and toggled as false. REMOVE THEM.

Thanks all.

Remove Fragments from Backstack using Navigation Component

popBackStack(, true) pops everything up to and inclusive to the first fragment. You've popped every fragment off the back stack. Seems like you want to use false, not true if you just want to return to the first fragment.

How can I clear every fragments in back stack using Navigation Component (for example when HTTP 401 triggeres) and sent to login fragment

Updated answer:

We can use (id of our Navigation Graph) for setPopUpTo() to clear backstack completely

val navOptions = NavOptions.Builder()
.setPopUpTo(, true)
navController.navigate(, null, navOptions)

Previous answer:

I implemented this solution, though it looks difficult

navController.graph = navController.graph.apply {
startDestination =
val navOptions = NavOptions.Builder()
.setPopUpTo(, true)
navController.navigate(, null, navOptions)

But it works and clears all back stack and only one loginFragment will be in the stack

Related Topics

Leave a reply