This gist is a workaround to this bug:
https://code.google.com/p/android/issues/detail?id=29472
No changes are needed to your current code but changing the extended fragment/activity class.
All you have to do is put this two classes in your code and make your activity extend MenuManagerActivity and your fragment MenuDelegatorFragment. If you are using Nested fragment you must make sure that all fragments containing nested Fragments with options menu also extend MenuDelegatorFragment (both if the parent fragment need an option menu both if it doesn't need it).
A suggestion that works very for every app: always, as first thing when you start a project, write a MyFragment and MyActivity class (or Base/Abstract whatever prefix suits you) and extend that with every single fragment/activity you write. It will be easier to handle cases like this.
No change is needed to your actual fragment apart from the extended class. Using a Viewpager, Actionbar Tabs, Navigation Drawer (hamburger menu) on Android pre-4.4 Kitkat made the menu created from the fragments (or nested fragments) unreliable, meaning that switching between pages, changing fragments etc caused the menu not to update in sync with the currently showed fragment.
Resulting in options menu items being visible when their fragment was not or vice-versa.
This workaround delegate all the handling of the option menu to the activity that will call the fragments methods to create the menu.
The fragment side of the thing disable the framework handling and register / unregister the fragment to the activity when the fragment come in / go out from the current view, which cause an invalidate on the menu.
There's also an issue with nested fragments: they may be left resumed and with "hint visibility" = true even if the parent fragment is detached. This code also take care of that situation.
There's a DEBUG flag in the fragment implementation you can use to check what's wrong if in your situation something is not working as you expect.
I don't know if work in 100% of the cases. But it works perfectly fine and reliably for me so I share it for everyone.
Let me know in comments if this worked for you. Suggestions are welcome!
Hi,
I've used somehow simpler solution to solve problem with hiding menus from nested fragments. In my nested fragments I added just one line of code:
I'm not sure if it handles all situations but it works for me. If the parent fragment is not visible (in my case the ViewPager is showing another 'main' fragment, the isMenuVisible() returns false. Otherwise it returns true.