使用导航组件导航到自身时如何显示后退按钮?

How to display back button when navigating to self with navigation component?

我的导航栏是这样设置的

with(ActivityHolderBinding.inflate(layoutInflater)) {
        setContentView(root)
        val fragment = supportFragmentManager.findFragmentByTag("holder") as NavHostFragment
        toolbar.setupWithNavController(fragment.navController,AppBarConfiguration(fragment.navController.graph))
        setSupportActionBar(toolbar)
    }

但这只在我导航到另一个片段时显示后退按钮,而不是在标记为开始目的地的片段上导航到自身时不显示。

根据this issue

setupActionBarWithNavController uses the current destination ID to determine if the Up button is shown, so the behavior you're seeing is working as intended.

You can have multiple destinations that use the same Fragment class, so just create a separate destination for recursive calls:

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

    <fragment
        android:id="@+id/categories"
        android:name="somepackage.categories.CategoryListFragment"
        tools:layout="@layout/catalog_category_list_frag">

        <action
            android:id="@+id/action_category_to_category"
            app:destination="@id/categoriesRecursive" />

        <action
            android:id="@+id/action_category_to_product_list"
            app:destination="@id/products_frag" />

        <argument
            android:name="categoryId"
            app:argType="integer"
            android:defaultValue="0" />

    </fragment>
    <fragment
        android:id="@+id/categoriesRecursive"
        android:name="somepackage.categories.CategoryListFragment"
        tools:layout="@layout/catalog_category_list_frag">

        <action
            android:id="@+id/action_category_to_category"
            app:destination="@id/categoriesRecursive" />

        <action
            android:id="@+id/action_category_to_product_list"
            app:destination="@id/products_frag" />

        <argument
            android:name="categoryId"
            app:argType="integer"
            android:defaultValue="0" />

    </fragment>
    ....
</navigation>

因此,通过使用两个不同的 ID,NavigationUI 可以区分您的第一个级别(不应显示向上箭头)与应显示向上箭头的级别。