Search code examples
androidandroid-fragmentsandroid-jetpack-navigation

Drawer menu blocked by fragment menu


So, I have an app that are using drawer menu and some fragments. But, when the fragment i'am on a fragment that have a menu, it completely blocked my drawer menu even if the burger icon is still visible.

Fragment with menu

But, when i press the back button and exit current Fragment with its own menu, the drawer menu works again. It seems like the menu from fragment are blocking the drawer menu. Here is my code for adding menu provider into fragment :

val menuHost: MenuHost = requireActivity()
    menuHost.addMenuProvider(
        this,
        viewLifecycleOwner,
        Lifecycle.State.RESUMED
    )

And here is my code for inflating the menu :

menuInflater.inflate(R.menu.main_menu, menu)
    val myActionMenuItem = menu.findItem(R.id.btn_search_menu)
    val searchView = myActionMenuItem.actionView as SearchView?
    searchView?.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
        override fun onQueryTextSubmit(query: String?): Boolean {
            (context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
                .hideSoftInputFromWindow(view?.windowToken, 0)

            return true
        }

        override fun onQueryTextChange(newText: String?): Boolean = false
    })

Solution

  • I just found the right answer, you need to return false in onMenuItemSelected if you want the AppBarConfiguration to take care of the navigation click again. It is the way of saying that we are now passing the handling of menu's click event back to the Jetpack Component.

        activity?.addMenuProvider(object : MenuProvider {
    
            override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
                // Do your inflation here
            }
    
            override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
                R.id.action -> {
                   // Do your stuff here
                   return true // Click event is now your responsibility
                }
                else -> false // Click event responsibility back to Android
            }
    
        })
    

    In your Activity nothing will change, you still need to override onSupportNavigateUp like this

    override fun onSupportNavigateUp(): Boolean {
        return navigateUp(navController, appBarConfiguration) || super.onSupportNavigateUp()
    }