Reputation: 325
I am trying to clear all fragments from the back stack when the home fragment is displayed. In the navigation graph I added this action
<fragment
android:id="@+id/loginFragment"
android:name="com.test.navTest.ui.fragment.LoginFragment"
android:label="fragment_login"
tools:layout="@layout/login_fragment"
>
<action
android:id="@+id/action_loginFragment_to_homeFragment"
app:destination="@id/homeFragment"
app:popUpTo="@+id/homeFragment"
/>
</fragment>
and In the login fragment. I tried
findNavController().navigate(LoginFragmentDirections.actionLoginFragmentToHomeFragment())
and
findNavController().navigate(R.id.action_loginFragment_to_homeFragment)
As I understand from the documentation here https://developer.android.com/guide/navigation/navigation-navigate
that popUpTo
clears all the stack until the destination. But nothing is cleared when I press back.
UPDATE: I changed this action to popUpTo=Login. It removed only the login fragment and not the 2 fragments before it. Should I add any parameter to the action of the fragments before the login
<action
android:id="@+id/action_loginFragment_to_homeFragment"
app:destination="@id/homeFragment"
app:popUpTo="@+id/loginFragment"
app:popUpToInclusive="true" />```
Upvotes: 3
Views: 4961
Reputation: 325
What worked for me on clearing all fragments in the backstack is to add the graph id in the popUpTo
value
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/splashFragment">
<fragment
android:id="@+id/loginFragment"
android:name="com.test.navTest.ui.fragment.LoginFragment"
android:label="fragment_login"
tools:layout="@layout/login_fragment">
<action
android:id="@+id/action_loginFragment_to_homeFragment"
app:destination="@id/homeFragment"
app:popUpTo="@+id/nav_graph"
app:popUpToInclusive="true" />
</fragment>
When I added popUpTo = @+id/login_fragment
. It removed the login fragment only.
Upvotes: 7