androiddrawerlayouthamburger-menuandroid-optionsmenu

Why is hamburger icon disabled when adding an options menu?


I have a DrawerLayout set up and everything is working fine. Until I create an options menu in one of my fragments via requireActivity().addMenuProvider(...). With that a tap on the hamburger icon doesn't open the drawer anymore. I can still slide it in from the left though. On other fragments that don't provide a menu the hamburger icon is working fine.

Is there a way to have a menu in some fragments and still have the hamburger icon open the drawer?

EDIT: This is from my MainActivity's onCreate method:

    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)

and this is from the fragment that provides a menu:

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)
}

Solution

  • ianhanniballake's comment brought me on the right track. This is what the onMenuItemSelected method should look like:

        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
            }
        }