Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigation architecture: How to manage proper navigation without using clearTask as it is deprecated

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.

like image 371
TapanHP Avatar asked Nov 15 '18 07:11

TapanHP


2 Answers

You need to use in your action next code

app:popUpTo="@+id/fragment_login"
app:popUpToInclusive="true"
like image 189
Eugene Avatar answered Nov 15 '22 00:11

Eugene


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.

like image 30
Alex Mofer Avatar answered Nov 15 '22 00:11

Alex Mofer