What is the use of invalidateOptionsMenu() in android - android

I am a newbie to android when I am going through a sample code for navigation drawer I found he called the method invalidateOptionsMenu() so I searched regarding its functionality but couldn't find an answer so can anyone please brief me its functionality and whenshould we use that.

This function tell android that it should redraw the menu. By default, once the menu is created, it won't be redrawn every frame (since that would be useless to redraw the same menu over and over again).
You should call this function when you changed something in the option menu (added an element, deleted an element or changed a text). This way android will know that it's time te redraw the menu and your change will appear.
Hope this answers your question

I use this method in combination with actionbar: When I need to populate actionbar with new menu items, I call invalidateOptionsMenu(), then onCreateOptionsMenu is called and I can inflate menu that I need. :-)
for more info see http://developer.android.com/reference/android/app/Activity.html#invalidateOptionsMenu()
or
Change options menu during runtime - invalidateOptionsMenu()

That would trigger another call to onCreateOptionsMenu where you can decide to display a new menu. It's basically the right way of replacing the current menu with a new one.

When Activity is created then the onCreateOptionsMenu method is called. Inside you can inject menu from menu.xml ol build it by hand. But if you want to change this menu during activity life you must call invalidateOptionsMenu();
eg:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (something) {
// buildOneMenu
} else {
// buildAnotherMenu
}
}
...
something = true;
invalidateOptionsMenu();

invalidateOptionsMenu() is used to say Android, that contents of menu have changed, and menu should be redrawn. For example, you click a button which adds another menu item at runtime, or hides menu items group. In this case you should call invalidateOptionsMenu(), so that the system could redraw it on UI. This method is a signal for OS to call onPrepareOptionsMenu(), where you implement necessary menu manipulations. Furthermore, OnCreateOptionsMenu() is called only once during activity (fragment) creation, thus runtime menu changes cannot be handled by this method.

Related

Android: Set menu visibility within a fragment

I have an android app that has a side menu and the main body of content is inside a fragment. So far there are 3 fragments (Home, Settings, Help). What I am trying to do is have the menu in the top right only appear in the home fragments.
Using
this.setHasOptionsMenu(false);
doesn't do anything so I am obviously using that wrong. Any ideas on how I can accomplish this?
Use:
menu.findItem(R.id.MENU_ITEM).setVisible(false);
For all of your menu items in the method onPrepareOptionsMenu(...). You should end up with something similar to this:
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.MENU_ITEM_ONE).setVisible(false);
menu.findItem(R.id.MENU_ITEM_TWO).setVisible(false);
menu.findItem(R.id.MENU_ITEM_THREE).setVisible(false);
}

What's the advantage of calling invalidateOptionsMenu when wanting to alter the created menu?

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.

Is supportInvalidateOptionsMenu() working?

I'm having the following issue - I have to update ActionBar menu in my application, after some things happen. I use ActionBarActivity from appcompat library.
So, I call supportInvalidateOptionsMenu() function, but menu won't update.
In debug mode I see, that onCreateOptionMenu method is calling, but menu not changed.
Am I doing something wrong? Or does it is ActionBarActivity issue?
After the system calls onCreateOptionsMenu(), it retains an instance of the Menu you populate and will not call onCreateOptionsMenu() again unless the menu is invalidated for some reason. However, 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().
for more details click here

What does onPrepareOptionsMenu do?

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);
}
}

How to get a hold of the ActionBar menu at UI setup time?

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().

Categories

Resources