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?
Use onPrepareOptionsMenu if you need to enable/disable, show/hide, or add/remove items after creating it.
To use the menu in your activity, you need to inflate the menu resource (convert the XML resource into a programmable object) using MenuInflater. inflate() .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With