7

I want to dynamically change the onCreateOptionsMenu items. I have rectified my problem and the only solution is to call onCreateOptionsMenu in onPostCreate but i don't know how to call it. I have already tried my solutions non works. Is it even possible..?

Ritesh Gune
  • 16,629
  • 6
  • 44
  • 72
Hussain Marvi
  • 455
  • 1
  • 5
  • 17

2 Answers2

23

Changing menu items at runtime (From Docs)

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

invalidateOptionsMenu() was added in API 11 to give us the ability to force onCreateOptionsMenu() to be called again.

invalidateOptionsMenu

NOTE:

In case of ICS and Honeycomb onCreateOptionsMenu() is called after onCreate() and onPostCreate() while in Gingerbread and earlier versions it is called after onCreate() but before onPostCreate().

Try following:

public static void refreshMenu(Activity activity)
{
    activity.invalidateOptionsMenu();
}
Ritesh Gune
  • 16,629
  • 6
  • 44
  • 72
17

use this,

invalidateOptionsMenu ();

  • Can you please give me an example..? – Hussain Marvi Apr 28 '14 at 05:36
  • when you call invalidateOptionMenu, it again calls onCreateOptionsMenu and then you have to handle what you want to do in onCreateOptionsMenu – Nandakishore Shetty Apr 28 '14 at 05:39
  • oh okay.. but where should i call InvalidateOptionsMenu(); ? the function that filling the optionsmenu is another java file and is fetching data from a web service.The problem is the delay.. if i toggle a break point and produce a delay then the whole thing is working fine.. – Hussain Marvi Apr 28 '14 at 05:42
  • invalidateOptionMenu is used to upldate the optionMenu and you can call it anywhere. – Nandakishore Shetty Apr 28 '14 at 05:45