我在单个 fragment 上添加选项菜单时遇到一些麻烦,因为它破坏了导航。这是我的代码
我有一个具有 NoActionBar
样式和布局的 Activity
<layout 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:fitsSystemWindows="true"
tools:context=".ui.MainActivity">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
<fragment
android:id="@+id/mainNavigationFragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/main_graph" />
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbarLayout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="top">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize" />
</com.google.android.material.appbar.AppBarLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:labelVisibilityMode="labeled"
app:menu="@menu/main_bottom_nav" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>
在 Activity onCreate
中,我进行了导航设置
private fun setupNavigation() {
val navController = findNavController(R.id.mainNavigationFragment)
//each fragment of botton nav
val appBarConfiguration = AppBarConfiguration(setOf(
R.id.actionSchedule,
R.id.actionPayment,
R.id.actionNotification,
R.id.actionAccount))
toolbar.setupWithNavController(navController, appBarConfiguration)
bottomNavigationView.setupWithNavController(navController)
}
override fun onSupportNavigateUp() =
findNavController(R.id.mainNavigationFragment).navigateUp()
在每个按钮导航 fragment 上我都有一些目的地,并且一切都按预期工作。
现在我需要仅在底部导航最右边的 fragment 上添加一个菜单,然后在这个特定 fragment 上我在 onCreate 中添加 setHasOptionsMenu(true)
并在 onCreateOptionsMenu
中添加菜单>,但菜单不出现。
然后我在 Activity onCreate
上添加 setSupportActionBar(toolbar)
。
现在菜单只出现在这个 fragment 上,但它破坏了任何目的地的所有“向上”(工具栏上的后向箭头)(出现后向箭头,但当我按下时什么也没有发生)。如果我删除 Activity 的 setSupportActionBar(toolbar)
,UP 会再次工作,但工具栏菜单不会。
我需要做什么才能使菜单仅在一个 fragment 中工作而不破坏其他任何内容? 谢谢
最佳答案
如果您使用 setSupportActionBar
,则必须使用 setupActionBarWithNavController()
,而不是按照 documentation 使用 toolbar.setupWithNavController
。 .
关于android - 如何使用导航组件在单个 fragment 上正确添加选项菜单而不破坏 "up behavior",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55380232/