Android 具有多个顶级目的地和子图的向上按钮导航——子图的所有子图也是顶级的

Android 具有多个顶级目的地和子图的向上按钮导航——子图的所有子图也是顶级的,android,android-architecture-navigation,Android,Android Architecture Navigation,导航图: <?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://s

导航图:

<?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/mobile_navigation"
    app:startDestination="@+id/navigation_home"
    >

    <fragment
        android:id="@+id/navigation_home"
        android:name="com.hanafey.android.waterstats.ui.home.HomeFragment"
        android:label="@string/title_home"
        tools:layout="@layout/fragment_home"
        />

    <!-- ......   -->

    <navigation
        android:id="@+id/navigation_graph_setup"
        android:label="Setup"
        app:startDestination="@id/navigation_setup"
        >
        <fragment
            android:id="@+id/navigation_setup"
            android:name="com.hanafey.android.waterstats.ui.setup.SetupFragment"
            android:label="@string/title_setup"
            tools:layout="@layout/fragment_setup"
            />
        <fragment
            android:id="@+id/navigation_find_or_create_results_sheet"
            android:name="com.hanafey.android.waterstats.ui.setup.FindOrCreateResultsSheetFragment"
            android:label="Find Or Create Results Sheet"
            tools:layout="@layout/fragment_find_or_create_results_sheet"
            />
        <fragment
            android:id="@+id/navigation_show_results_sheet_details"
            android:name="com.hanafey.android.waterstats.ui.setup.FindOrCreateResultsSheetDetailsFragment"
            android:label="Find Or Create Result Sheet Details"
            tools:layout="@layout/fragment_file_find_or_initialize_result"
            />
    </navigation>
</navigation>

问题是子图
R.id.navigation\u graph\u setup
的所有成员都变为顶级,并且不显示向上按钮。所需的行为只是子图的起始目标是顶层。

答案很简单,不要将子图标记为顶层。而是将子图的起始目标标记为顶层。这意味着您需要在图形xml和代码中保持一致。如果在代码中将子图指定为top,而不是将起始目标设置为top,则会更好,但如果在运行时更改起始目标,则这会很复杂

“androidx.navigation.ui.AbstractAppBarOnDestinationChangedListener”中的代码显示了如何通过查看目标,然后递归查看其所有父级来推断顶层

val topLevelDid = setOf(
    R.id.navigation_home,
    R.id.navigation_septic,
    R.id.navigation_notifications,
    R.id.navigation_graph_setup,
)
appBarConfiguration = AppBarConfiguration(topLevelDid)
setupActionBarWithNavController(navController, appBarConfiguration)