A month or so ago, the Android team deprecated onCreateOptionsMenu and onOptionsItemSelected, as well as setHasOptionsItemMenu. This unfortunately broke all of my code.
My app has a lot of fragments, and when the user navigates to them, I always made sure that the menu items would disappear and reappear on navigating back, with the following code:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
menu.clear()
}
This code worked well and was really simple. Now that the Android team has deprecated (why?) setHasOptionsMenu, I cannot recreate this code.
I understand the new syntax for inflating menu items and handling menu item click events, although I cannot figure out -- for the life of me -- how to hide the menu in a fragment and then show it again on navigation back using the new menu provider API.
Here's what I've tried:
Navigating to the fragment:
if (supportFragmentManager.backStackEntryCount == 0) {
supportFragmentManager.commit {
replace(R.id.activityMain_primaryFragmentHost, NewProjectFragment.newInstance(mainSpotlight != null))
addToBackStack(null)
}
}
getRootMenuProvider function in ActivityFragment interface:
interface ActivityFragment {
val title: String
companion object {
fun getRootMenuProvider() = object : MenuProvider {
override fun onPrepareMenu(menu: Menu) {
for (_menuItem in menu.children) {
_menuItem.isVisible = false
}
}
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return false
}
}
}
}
Using the getRootMenuProvider function:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val menuHost: MenuHost = requireActivity()
menuHost.addMenuProvider(ActivityFragment.getRootMenuProvider())
}
MainActivity (trying to restore the menu items to their previous state):
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
for (_menu in menu.children) {
_menu.isVisible = true
}
return super.onPrepareOptionsMenu(menu)
}
override fun onBackPressed() {
super.onBackPressed()
findViewById<BottomNavigationView>(R.id.activityMain_bottomNavigationView)?.visibility = View.VISIBLE
invalidateOptionsMenu()
}
This hides the items in the fragment, but the items still remain hidden after navigating back until the user reloads the activity by rotating their screen, or doing something similar.
How to hide the menu items in a fragment and reappear them on navigation back with the new menu provider API?