Use of `onPrepareOptionsMenu()` on Android 3.0+-ThrowExceptions

Exception or error:

I’m curious as to how (if at all) onPrepareOptionsMenu(Menu) (and by extension, onPreparePanel(int, View, Menu)) is used on Android 3.0+ when targeting API 11 or greater.

My thinking is as follows:

An Activity‘s ActionBar receives its content from onCreateOptionsMenu(Menu) where you can either inflate an XML menu resource, add items directly, or some combination of both. Any fragments of the activity will also receive this call and have the option of doing the same.

To update the items on the ActionBar you can either hold on to the Menu instance or call invalidateOptionsMenu() which will then wind up calling onCreateOptionsMenu(Menu) again.

Thus, is onPrepareOptionsMenu(Menu) then only still around to support legacy applications which do not target API 11 or newer?

Does calling getActionBar().hide() and getActionBar().show() trigger a call to onPrepareOptionsMenu(Menu) perhaps?

Does adding or removing a fragment somehow trigger this?

How to solve:

From my extensive testing, it strangely appears to work exactly like on pre-3.0 versions of the platform, only being invoked when the overflow menu is opened. The callback did not fire on either of the events listed in the original question.

A perhaps obvious but noteworthy fact: The entire menu is accessible on this callback so manipulation of items which are visible on the action bar, in the overflow menu, and/or hidden is possible.

###

Sice I recently had similar questions and stumpled upon this one, I’d like to add for later readers:
Yes, onPrepareOptionsMenu still does work.
However, you should just invoke the standard implementation for Honeycomb devices (i.e. if ( android.os.Build.VERSION.SDK_INT >= 11 ) return super.onPrepareOptionsMenu(menu);) and use invalidateOptionsMenu() (via reflection, if necessary) and onCreateOptionsMenu() instead, esp. when using showAsAction. Otherwise, the menu won’t be updated until it’s opened. For example, if you add some entries when an item is selected, the items will magically appear in the action bar when the menu’s opened, not when the item’s becoming selected. Same goes for deselection and hiding the menu items.

Leave a Reply

Your email address will not be published. Required fields are marked *