我设置了 DrawerLayout,一切正常。直到我通过
requireActivity().addMenuProvider(...)
在我的一个片段中创建选项菜单。这样,点击汉堡图标就不再打开抽屉了。不过我仍然可以将其从左侧滑入。在不提供菜单的其他片段上,汉堡图标工作正常。
有没有办法在某些片段中有菜单,并且仍然让汉堡包图标打开抽屉?
编辑:这是来自我的 MainActivity 的 onCreate 方法:
val navController = findNavController(R.id.nav_host_fragment)
val topDest = setOf(R.id.scanner_fragment, R.id.products_fragment, R.id.categories_fragment)
appBarConfiguration = AppBarConfiguration(topDest, binding.drawerLayout)
setupActionBarWithNavController(navController, appBarConfiguration)
binding.navView.setupWithNavController(navController)
这是来自提供菜单的片段:
private val menuProvider = object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
when (menuItem.itemId) {
R.id.flashlight -> {
val iconId = toggleFlashLight()
menuItem.icon = ContextCompat.getDrawable(requireContext(), iconId)
}
}
return true
}
}
override fun onStart() {
super.onStart()
requireActivity().addMenuProvider(menuProvider)
}
override fun onPause() {
super.onPause()
requireActivity().removeMenuProvider(menuProvider)
}
ianhanniballake 的评论让我走上了正轨。这就是 onMenuItemSelected 方法应该是什么样子的:
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return when (menuItem.itemId) {
R.id.flashlight -> {
val iconId = toggleFlashLight()
menuItem.icon = ContextCompat.getDrawable(requireContext(), iconId)
true
}
else -> false
}
}