Home > Blockchain >  How to add option menu in fragment with new menuprovider
How to add option menu in fragment with new menuprovider

Time:12-16

How do i add options menu on fragment with the new Menu Provider, specifically searchview menu?

override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
    menuInflater.inflate(R.menu.explore, menu)
}

override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
    when (menuItem.itemId) {
        R.id.btn_search_menu -> {
            Log.d(TAG, "onMenuItemSelected: Clicked")
        }
    }
    return true
}

i tried using this code but the menu didn't get inflated

CodePudding user response:

As seen in the Activity 1.4.0-alpha01 release notes (where the MenuProvider API was added), creating a MenuProvider is only half of the problem - you then need to call addMenuProvider on a MenuHost like your activity:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    // The usage of an interface lets you inject your own implementation
    val menuHost: MenuHost = requireActivity()
  
    // Add the MenuProvider to the MenuHost
    menuHost.addMenuProvider(
      this, // your Fragment implements MenuProvider, so we use this here
      viewLifecycleOwner, // Only show the Menu when your Fragment's View exists
      Lifecycle.State.RESUMED // And when the Fragment is RESUMED
    )
}
  • Related