简体   繁体   中英

Back and Up Button with different behavior on Jetpack Navigation Component

I'm trying to create a destination that when I press back/up the app close. So I set the popUpTo for the start destination and set the popUpToInclusive to true. The problem is, when I press the Back Button, app close as intended, but If I press Up Button(toolbar back arrow), activity is recreated...

nav graph:

<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_graph"
    app:startDestination="@id/call">

    <fragment
        android:id="@+id/call"
        android:name="com.example.navigationplayground.main.CallFragment"
        android:label="Call"
        tools:layout="@layout/fragment_call" />
    <fragment
        android:id="@+id/agenda"
        android:name="com.example.navigationplayground.main.AgendaFragment"
        android:label="Agenda"
        tools:layout="@layout/fragment_agenda" >
        <action
            android:id="@+id/openDetail"
            app:destination="@id/detailFragment"
            app:popUpTo="@+id/call"
            app:popUpToInclusive="true" />
    </fragment>
    <fragment
        android:id="@+id/detailFragment"
        android:name="com.example.navigationplayground.main.DetailFragment"
        android:label="Detail"
        tools:layout="@layout/fragment_detail"/>

</navigation>

sample app: https://github.com/LipeDuoli/navPlayground

look the behavior of back and up button from detail screen

The problem is that up and back have different behavior.

The Up button never exits your app

If a user is at the start destination, the Up button should not be shown. When your app is launched using a deep link on another app's task, Up should take users to the hierarchical parent destination and not back to the other app.

If you wan't to follow guidelines, one possible way to solve your situation is to change this line

val appBarConfiguration = AppBarConfiguration(setOf(R.id.call, R.id.agenda))

To this one

val appBarConfiguration = AppBarConfiguration(setOf(R.id.call, R.id.agenda, R.id.detailFragment))

That basically means that your start destination could be one of the list above. And start means that user will exit the app after back pressing on this screen.

More details:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM