Jetpack 导航:隐藏工具栏中的标签

Jetpack Navigation: Hide label in toolbar

新的 Jetpack Navigation 使用 navigation.xml 文件中的 label 属性根据显示的目标片段自动更新工具栏的标题。

我不想在我的目标片段中显示任何标题,所以我可以在这个地方放一个 SearchView

我已经尝试过 android:label="@null" 但工具栏的标题只是退回到应用程序的标题。在 onCreateOptionsMenu() 回调中调用 menu.clear() 也没有任何效果。

如何仅在特定目标片段中从我的工具栏菜单中完全删除标题?

一种解决方案是在您的特定片段中隐藏操作栏,并使用您的搜索视图等在片段中创建一个新的 ActionBar。根据它是支持还是普通操作栏,它在 onCreateView:

中会是这样的
val act: MainActivity = activity as MainActivity
    act.supportActionBar?.hide()

activity?.actionBar?.hide()

显然,您必须如上所述在片段布局中设置自己的操作栏。您可以使用类似 com.google.android.material.appbar.AppBarLayoutandroidx.appcompat.widget.Toolbar 的东西,或者任何自定义布局,无论是来自图书馆还是您自己。

作为替代方案,updating UI components with NavigationUI 的 android 指南表明您可以像这样使用 addOnDestinationChangedListener

navController.addOnDestinationChangedListener { _, _, _ ->
    toolbar.title = ""
}

此解决方案不需要清除每个片段中的标题。

在 navigation.xml

中删除 android:label="" 中的值
    <fragment
    android:id="@+id/navigation_profile"
    android:name="com.example.app.profile.ProfileFragment"
    android:label=""
    tools:layout="@layout/profile_fragment" >