Search code examples
androidandroid-architecture-components

Exit from nested Navigation Graph


I have 3 graphs: 'Main', '1', and '2'

App starts to 'Main', we check if user is logged in, then we go to either '1' or '2' depending on logged in state.

This works as expected.

Here's the issue:

When the user clicks 'back' from the '1' or '2' main screen, the app navigates back to 'Main'.

Here's the expected result:

When the user clicks 'back' from the '1' or '2' main screen, the app should exit.

How do I exit from the top level fragment of a nested graph?

Here's my 'Main' navigation graph:

<?xml version="1.0" encoding="utf-8"?>
<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/main_navigation"
    app:startDestination="@id/fragment_main">

    <fragment
        android:id="@+id/fragment_main"
        android:name="com.my.app.fragments.MainFragment"
        android:label="MainFragment"
        tools:layout="@layout/fragment_main">
        <action
            android:id="@+id/action_fragment_main_to_logged_out_navigation"
            app:destination="@id/logged_out_navigation"
            app:enterAnim="@anim/nav_default_enter_anim"
            app:exitAnim="@anim/nav_default_exit_anim"
            app:launchSingleTop="true"
            app:popEnterAnim="@anim/nav_default_pop_enter_anim"
            app:popExitAnim="@anim/nav_default_pop_exit_anim"
            app:popUpTo="@+id/main_navigation"
            app:popUpToInclusive="true" />
        <action
            android:id="@+id/action_fragment_main_to_logged_in_navigation"
            app:destination="@id/logged_in_navigation"
            app:enterAnim="@anim/nav_default_enter_anim"
            app:exitAnim="@anim/nav_default_exit_anim"
            app:launchSingleTop="true"
            app:popEnterAnim="@anim/nav_default_pop_enter_anim"
            app:popExitAnim="@anim/nav_default_pop_exit_anim"
            app:popUpTo="@+id/main_navigation"
            app:popUpToInclusive="true" />
    </fragment>
    <include app:graph="@navigation/logged_in_navigation" />
    <include app:graph="@navigation/logged_out_navigation" />
</navigation>

Solution

  • I have been facing the same issue. After some google, I have found an issue on the Google Issue Tracker: https://issuetracker.google.com/issues/140124444

    It says, This is intended behavior and won't be fixed. And As per the Principles of Navigation, you should not be popping the start destination off your back stack.