Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onPrepareOptionsMenu is not called

I'm having trouble getting onPrepareOptionsMenu() to work correctly. No matter what I try, I can't get it to be called.

The architecture of my application is as follows: my main Activity contains a Fragment which holds a ViewPager, which in turn has four child Fragment instances. Currently, I'm (successfully) populating the initial options menu in the Activity with onCreateOptionsMenu(), but I wish to add some extra options corresponding to each active child Fragment.

Within my child Fragments, I've made sure that setHasOptionsMenu(true) is being called in onCreate() and that getSherlockActivity().supportInvalidateOptionsMenu() is called in onActivityCreated(). In the main Activity, onCreateOptionsMenu() is called once after the child Fragments are instantiated, regardless of whether they contain supportInvalidateOptionsMenu() or not. It is subsequently called again whenever the Fragment in the Pager is replaced.

I've tried moving the onPrepareOptionsMenu() code up a level to the parent Fragment and to the main Activity - to no avail, which suggests that the problem is not related to my use of nested Fragments. I've also tried moving the onCreateOptionsMenu() method down from the main Activity to both fragments, where it goes uncalled.

If anyone has any idea what's going on here I'd be very grateful, as I've been stuck on this for two days now.

UPDATE - I've worked out exactly what the problem is now, only I'm still not sure how to fix it. I'm testing on 4.2 and it seems that onCreateOptionsMenu() is called after onResume() in the Activity - as seen in onCreateOptionsMenu called after onResume on JB 4.2. I assume this means that fragments can't call onPrepareOptionsMenu() because the menu doesn't even exist until after they're instantiated. So how do I solve this?

like image 382
steffandroid Avatar asked Jun 19 '13 16:06

steffandroid


1 Answers

It was, somewhat inevitably, an issue with ActionBarSherlock that I'd overlooked when checking its issues page on github. Basically, the functionality for options menus in nested fragments has not yet been added, see: https://github.com/JakeWharton/ActionBarSherlock/issues/828. My solution for now is to replace Watson.java with one of the modified files in the comments.

like image 171
steffandroid Avatar answered Oct 19 '22 03:10

steffandroid