call onCreateOptionsMenu in onPostCreate

HussainMarvi picture HussainMarvi · Apr 28, 2014 · Viewed 9.9k times · Source

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..?

Answer

Ritesh Gune picture Ritesh Gune · Apr 28, 2014

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