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.

<fragment
android:id="@+id/signInFragment"
android:name="com.glee.incog2.android.fragment.SignInFragment"
android:label="fragment_sign_in"
tools:layout="@layout/fragment_sign_in" >
<action
android:id="@+id/action_signInFragment_to_usersFragment"
app:destination="@id/usersFragment"
app:launchSingleTop="true"
app:popUpTo="@+id/main_nav_graph"
app:popUpToInclusive="true" />
</fragment>

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

findNavController(fragment).navigate(
SignInFragmentDirections.actionSignInFragmentToUserNameFragment())

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(R.id.firstFragment, 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 R.id.nav_graph (id of our Navigation Graph) for setPopUpTo() to clear backstack completely

val navOptions = NavOptions.Builder()
.setPopUpTo(R.id.nav_graph, true)
.build()
navController.navigate(R.id.loginFragment, null, navOptions)

Previous answer:

I implemented this solution, though it looks difficult

navController.graph = navController.graph.apply {
startDestination = R.id.loginFragment
}
val navOptions = NavOptions.Builder()
.setPopUpTo(R.id.loginFragment, true)
.build()
navController.navigate(R.id.loginFragment, null, navOptions)

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



Related Topics



Leave a reply



Submit