Before I ask the question let me give some additional info:
I have a Fragment which adds a MenuItem in the onCreateOptionsMenu. The added MenuItem also has a custom ActionProvider added to it.
The custom ActionProvider doesn't use a ActionView but instead prepares a SubMenu with certain items to choose from. For this reason I've setup the ActionProvider as follows:
I return null in the onCreateActionView method
hasSubMenu() returns true
In onPrepareSubMenu(SubMenu Menu) I first clear the current menu, afterwards add the needed items
I correctly handle the onMenuItemClick in the ActionProvider
Since I'm using ActionBarSherlock, my ActionProvider extends com.actionbarsherlock.view.ActionProvider rather then android.support.v4.view.ActionProvider (don't know if it should make any difference, but at this point I don't know what does)
This all goes well on devices with Android versions higher then 3.0. I see the added MenuItem, it has the correct SubMenu (from the bound ActionProvider) and the correct actions take place for each menu option. But with devices running Android versions below 3.0 (I could only test this on a device running 2.3.6) something weird happens; hence the following question.
Google clearly states:
"onPerformDefaultAction()
The system calls this when the menu item is selected from the action overflow and the action provider should perform a default action for the menu item.
However, if your action provider provides a submenu, through the onPrepareSubMenu() callback, then the submenu appears even when the action provider is placed in the action overflow. Thus, onPerformDefaultAction() is never called when there is a submenu."
Taken from: http://developer.android.com/guide/topics/ui/actionbar.html#CreatingActionProvider
From the excerpt I take it onPerformDefaultAction() should NEVER be called in my custom ActionProvider. Yet on devices running Android version 2.3.6 the onPerformDefaultAction() DOES get called, which also prevents the SubMenu from showing.
My question is; why does the onPerformDefaultAction() gets called instead of the onPrepareSubMenu(SubMenu Menu)? I need a submenu on devices running Android 2.3.6 as well..
EDIT:
I managed to fix my problem using the same technique from the SubMenus.java from the ActionbarSherlock demo-code. This involves adding a SubMenu instead of a custom ActionProvider to the menu in onCreateOptionsMenu(Menu menu), and attaching OnMenuItemClickListener to each MenuItem there.
The workaround is nice and simple. Still, this does not answer my question as to why custom ActionProviders do not work.
Related
I need to program something like the image:
When I long click a item in a ListView two options appear in the toolbar, to delete the item or cancel the action.
I want to make exactly like that, I do not want a context menu (which I know how to do).
Is it possible to do this with simple code? If no, can I accomplish that manipulating the toolbar? How can I do that?
PS: I can only use native code.
You need to use contextual Action Mode Over Toolbar.For Using Action Mode we need to extend our class with ActionMode.Callback. Its a Callback interface for action modes. Supplied to startSupportActionMode(Callback) (Callback)}, a Callback configures and handles events raised by a user’s interaction with an action mode.You need to override following method.
onCreateActionMode(ActionMode, Menu) once on initial creation.
onPrepareActionMode(ActionMode, Menu) after creation and any time the ActionMode is
invalidated.
onActionItemClicked(ActionMode, MenuItem) any time a contextual action button is
clicked.
onDestroyActionMode(ActionMode) when the action mode is closed.
Most of the times whenever there is a talk of updating the ActionBar options (like displaying/hiding items) I see people doing that with calling invalidateOptionsMenu method (or AppCompat equivalent) to force that onCreateOptionsMenu again, which essentialy does the same thing it did before which is inflating the menu again, setting up all the menu items etc. All this work, just to change a visibility of say... one item.
Same thing I see in all the samples I've seen from Google. And for the life of me I cannot figure out the reason why all this uneceseary overhead is done(inflating the menu etc) when all of this could be done if you only holded the Menu reference localy, and invoke a custom method say... adjustMenu(Menu menuReference), which would not have to inflate the menu and create it again, but just make neceseary modifications on the already created Menu. So something of these sorts:
https://stackoverflow.com/a/7066901/905938
Most likely there is a reason for doing it Google way (through forcing onCreateOptionsMenu again and again), since Google samples do the same, but since I couldn't figure out the reason on my own, maybe someone could give me a hand here, and point me to that reason.
You should only really be inflating your options menu within onCreateOptionsMenu().
when all of this could be done if you only holded the Menu reference localy
You can do this locally via the method onPrepareOptionsMenu(Menu menu). This would actually be a great place to set a menu item's visibility. As to the question of the significance to the call invalidateOptionsMenu(); it's purpose should be looked at from two viewpoints.
Before API 11 and the introduction of fragments, the call to invalidateOptionsMenu would signal that the methods onCreateOptionsMenu() and onPrepareOptionsMenu() should be called again. Since activities normally have only one options menu, the menu object could afford to be kept in memory so as to make subsequent calls to onCreateOptionsMenu() more responsive.
Since the release of API 11, the options menu could no longer be stored in memory as before, since the introduction of fragments meant that the activity as well as each of its fragments could have its own options menu, and as fragments can be changed dynamically during the lifetime of the activity, it would be inefficient to store a bunch of options menus for each fragment as these fragments would not be guaranteed to stay on screen. Remember as well that in API 11+, options menu items can be displayed on the action bar. Changing your phone's configuration from portrait to landscape would mean more options menu items could be displayed on the action bar, thus items present in the overflow menu could now be moved to the action bar itself. An alternate albeit slower solution would be to simply rebuild all onscreen fragments' options menus from scratch. So for API 11+, the call to invalidateOptionsMenu() can be viewed as a signal to indicate that the layout of an activity's fragments have changed, and that the methods onCreateOptionsMenu() and onPrepareOptionsMenu() should be called for both the activity and the fragments it is currently hosting.
Check out the entry on invalidateOptionsMenu(Activity activity) here for more information as to why invalidateOptionsMenu is used.
I want to make Option Menu for Android, I have visit this site. In their script, I found onPrepareOptionsMenu, I try to compile and run using Android 2.3.3 compiler with and without onPrepareOptionsMenu, both works, but I didn't see any difference.
public boolean onCreateOptionsMenu(Menu menu){
//code here
}
public boolean onOptionsItemSelected(MenuItem item){
//code here
}
public boolean onPrepareOptionsMenu(Menu menu){
//code here
}
What is actually onPrepareOptionsMenu method do? Is that method important? Could I just delete the method?
Addition
Oh, I also hear about Action Bar in Android 3.0, it says that Action Bar is the alternative way for make Option Menu, and it using onPrepareOptionsMenu. Is that right?
Thank you...
Take a look in the API:
Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.
If you want to alter the menu before it's shown to the user, you can put code to do that into onPrepareOptionsMenu. I've used that dynamically to disable some menu options in some circumstances.
As an example of when one might want to disable a menu option, I had an app where there was a way of specifying a destination. One of my menu options was to calculate a route to the destination. However, if a destination wasn't specified, that option didn't apply, so I used onPrepareOptionsMenu to disable that menu option when it wasn't applicable.
From Android 3.0 and beyond, there's the ActionBar, which is a menu bar. The most important items go into the ActionBar itself, but then there's an overflow for when there's not enough room on the action bar. One can specify that menu items should always be in the overflow menu and never on the action bar itself. On some devices, the action bar overflow corresponds to the permanent menu button on the device, whereas on other devices which don't have a menu button the overflow menu is seen on the right hand side of the action bar as three vertical dots.
onCreateOptionsMenu is called once, when your activity is first created. If it returns false, no option menu is shown and onPrepareOptionsMenu is never called.
If onCreateOptionsMenu returns true, onPrepareOptionsMenu is also called before the activity is displayed, and also every time the options menu is invalidated. Use onPrepareOptionsMenu if you need to enable/disable, show/hide, or add/remove items after creating it.
If your menu does not change, use onCreateOptionsMenu.
example
#Override
public void onPrepareOptionsMenu(#NonNull Menu menu) {
super.onPrepareOptionsMenu(menu);
if(!URLUtil.isValidUrl(news.geturl())){
menu.findItem(R.id.share).setVisible(false);
}
}
For some reason, onCreateOptionsMenu() is called AFTER onResume() in my app... Therefore, I just can't get a hold of the menu while I'm setting up my UI (between onCreate() and onResume()), which results in not being able to setup the corresponding action items for my ActionBar...
The only work-around I've found so far is to manually call invalidateOptionsMenu() right before onCreate() returns; that way onCreateOptionsMenu() is immediately called, I get a hold of the menu and then I can finally add the desired action items.
Has anyone experienced this issue? How are you supposed to programmatically setup your action items given onCreateOptionsMenu() is called after onResume()?
My app is running on JellyBean, it uses the built-in ActionBar (no ActionBarSherlock), android:minSdkVersion="14" and android:targetSdkVersion="16"
First consider that perhaps you shouldn't be doing this. It sounds like your idea might go against typical design patterns for Android. If your menu is changing in response to a user selection, for example, you should use contextual action mode instead.
From the Action Bar API Guide:
As a general rule, all items in the options menu (let alone action items) should have a global impact on the app, rather than affect only a small portion of the interface. [...] So, even before deciding whether a menu item should appear as an action item, be sure that the item has a global scope for the current activity.
From the Menu API Guide:
You should never change items in the options menu based on the View currently in focus. When in touch mode (when the user is not using a trackball or d-pad), views cannot take focus, so you should never use focus as the basis for modifying items in the options menu. If you want to provide menu items that are context-sensitive to a View, use a Context Menu.
Barring that, if you do want to change the menu items as you have described, you should make the change in onPrepareOptionsMenu(). When the event occurs that requires changing the menu items, put the relevant information into a field and call invalidateOptionsMenu(). Override onPrepareOptionsMenu() and check the value of the field to determine which menu items to add/remove.
(It would also work to call invalidateOptionsMenu() and override onCreateOptionsMenu() to modify which menu items should be shown, although this approach is not recommended.)
More from the Menu API Guide:
You should use onCreateOptionsMenu() only to create the initial
menu state and not to make changes during the activity lifecycle.
If you want to modify the options menu based on events that occur
during the activity lifecycle, you can do so in the
onPrepareOptionsMenu() method.
This method passes you the Menu object as it currently exists so you
can modify it, such as add, remove, or disable items. (Fragments also
provide an onPrepareOptionsMenu() callback.)
On Android 2.3.x and lower, the system calls onPrepareOptionsMenu()
each time the user opens the options menu (presses the Menu button).
On Android 3.0 and higher, the options menu is considered to always be
open when menu items are presented in the action bar. When an event
occurs and you want to perform a menu update, you must call
invalidateOptionsMenu() to request that the system call
onPrepareOptionsMenu().
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?
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.