I have an activity that hosts few fragments.
Once the first fragment comes to the activity, it inflates some menu (actually just one action button) on AppBar layout of the activity:
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.menu_info, menu)
}
Once user is navigated to the second fragment within the same activity this action button should be hidden. I cannot achieve this (see my solutions below).
So, generally the question is:
How to hide menu from the activity AppBarLayout only for some fragments in the backstack?
NOTE: I don't need to hide the whole Toolbar (the title still should be shown, I want to hide only the action button!)
I tried different solutions that unfortunately don't work:
- Call setHasOptionsMenu(false) in the second fragment (tried both in onCreate and in onCreateView)
- Call activity.invalidateOptionsMenu() in different callbacks of the fragment and then try to hide the element of menu in onCreateOptionsMenu that should be called again after invalidate call. But I see it is not called even after invalidate call:
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menu.forEach {
it.isVisible = false
}
}
Also tried to combine all these solution but it does not work - the button is still shown on the second fragment.
onCreateOptionsMenu is already deprecated. You should use the MenuProvider api instead.
On your first fragment or the fragment where you want to show specific menu: