androidandroid-architecture-navigationfragment-backstack

Android - pop Back Stack with toolbar button in a single activity app


I have a single activity application (Java). If the user is not logged in the first thing he sees is a welcome screen where he can sign in and then move to the home fragment. If the user is signed in, the user goes directly to the home fragment.

The app has a number of tabs and secondary screens, each of them in fragments.

The toolbar is visible all the time and includes a sign out button. If the user signs out, he should move to the Welcome screen and the whole back stack should be removed.

I've previously tried this with multiple activities and it's straightforward because I've used:

startActivity(new Intent(TabsActivity.this, LoginActivity.class));
finish();

However, if I use finish, the app simply closes when I click sign out.

When moving from the splash screen to the welcome screen I had no problem popping the back stack because I knew the "from" and "to" fragments. Using the Navigation Component I had this in the NavGraph

<action
        android:id="@+id/action_splashScreenFragment_to_homeFragment"
        app:destination="@id/homeFragment"
        app:popUpTo="@id/splashScreenFragment"
        app:popUpToInclusive="true"/>
<action
        android:id="@+id/action_splashScreenFragment_to_welcomeFragment"
        app:destination="@id/welcomeFragment"
        app:popUpTo="@id/splashScreenFragment"
        app:popUpToInclusive="true"/>

And then I'd use

Navigation.findNavController(view)
   .navigate(R.id.action_splashScreenFragment_to_welcomeFragment);

In this case however, since the Sign Out button is in the toolbar, it can be accessed anywhere in the app. Navigation to the welcome screen is handled in the MainActivity.

navController.navigate(R.id.welcomeFragment);

Like I said, I tried adding finish() and that closed the whole application.

I also tried adding

navController.popBackStack(R.id.welcomeFragment, true);

and

navController.popBackStack(R.id.homeFragment, true);

but none worked.

How can I move to the Welcome Screen after sign out and remove the back stack?

UPDATE:

I tried the following:

<action
    android:id="@+id/action_global_welcomeFragment"
    app:destination="@id/welcomeFragment"
    app:popUpTo="@id/welcomeFragment"
    app:popUpToInclusive="true" />

and in MainActivity:

navController.navigate(R.id.action_global_welcomeFragment);

But when I click on the back button once sign out takes me to the Welcome Screen, I still can return to the previous screen.


Solution

  • You can add the splash screen as a Global Destination. Say the action has a name of globalSplashScreenAction, you would access it like navGraphDirections.globalSplashScreenAction

    You can right-click the splash screen destination from the navigation graph UI and set it as a global destination.

    enter image description here