5

While using navigation architecture as from here , here clearTask is deprecated.

My scenario is this: There are 2 screens Login and Registration, both have links to each other. So you can go to Registration from Login and also Login from Registration. But on back Press App should be closed.

It could simply be done by just adding clearTask to both actions as below.

<?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/nv_auth_phase"
    app:startDestination="@id/fragment_login">

    <fragment
        android:id="@+id/fragment_login"
        android:name="com.jobhook.ui.auth.login.LoginFragment"
        android:label="LoginFragment"
        tools:layout="@layout/fragment_login">
        <action
            android:id="@+id/nv_action_login_to_registration"
            app:clearTask="true"
            app:destination="@id/fragment_registration" />

    </fragment>


    <fragment
        android:id="@+id/fragment_registration"
        android:name="com.jobhook.ui.auth.registration.RegistrationFragment"
        android:label="RegistrationFragment"
        tools:layout="@layout/fragment_registration">


        <action
            android:id="@+id/nv_action_registration_to_login"
            app:clearTask="true"
            app:destination="@id/fragment_login" />
    </fragment>
</navigation>

But as it was deprecated I have tried other solution like adding popUpTo -> navigation graph's Id, making launchSingleTop to true in both actions. Nothing seems to work in my scenario.

I have checked this question also but didn't get a solution.

TapanHP
  • 5,097
  • 5
  • 33
  • 64

2 Answers2

8

You need to use in your action next code

app:popUpTo="@+id/fragment_login"
app:popUpToInclusive="true"
Eugene
  • 141
  • 6
0

Set your NavHostFragment defaultNavHost value false,

<fragment
    android:name="androidx.navigation.fragment.NavHostFragment"
    app:defaultNavHost="false"
    app:navGraph="@navigation/nav_graph"
    ... />

The app:defaultNavHost="true" attribute ensures that your NavHostFragment intercepts the system Back button. Note that only one NavHost can be the default. If you have multiple hosts in the same layout (two-pane layouts, for example), be sure to specify only one default NavHost.