Unable to clear the back stack of all fragments with Navigation Components

Viewed 565

I am using the Android Navigation Components and am facing one weird issue. I am not able to clear the back stack for the up button, no matter what I tried.

My Navigation graph looks like this:

Navigation Graph

Let's take the LoginFragment for example,

<fragment
    android:id="@+id/loginFragment"
    android:name="com.yashovardhan99.firebaselogin.LoginFragment"
    android:label="Login"
    tools:layout="@layout/fragment_login" >
    <action
        android:id="@+id/action_loginFragment_to_welcomeFragment"
        app:destination="@id/welcomeFragment"
        app:popUpTo="@+id/nav_graph"
        app:popUpToInclusive="true" />
</fragment>

The Java code to navigate is:

navController.navigate(
        LoginFragmentDirections.actionLoginFragmentToWelcomeFragment());

I have set the PopUpTo to the graph ID and set Inclusive to true. This should clear the back stack when moving to WelcomeFragment. However, the WelcomeFragment still shows the Up button on the action bar and pressing it takes me back to the PreLoginFragment (which is the home destination for the graph). Strangely, pressing the back button takes me out of the app as expected.

1 Answers

I solved it using AppBarConfiguration

val appBarConfiguration = AppBarConfiguration
            .Builder(
                    R.id.preLoginFragment,
                    R.id.welcomeFragment
              )
            .build()

Then, instead of setupActionBarWithNavController(this, navController) you need to call setupActionBarWithNavController(this, navController, appBarConfiguration)

Here I am declaring two top level fragments where the back arrow won't be shown in the app bar.

Related