使用导航组件导航到self时,如何显示后退按钮



我已经像这个一样设置了导航栏

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

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

根据此问题:

setupActionBarWithNavController使用当前目标ID来确定是否显示"向上"按钮,因此您看到的行为按预期工作。

您可以有多个使用相同Fragment类的目的地,所以只需为递归调用创建一个单独的目的地:

<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可以区分您的第一个级别(不应显示向上箭头(和应显示向下箭头的级别。

最新更新