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..?
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() . Save this answer.
onCreate() method calls the setContentView() method to set the view corresponding to the activity. By default in any android application, setContentView point to activity_main. xml file, which is the layout file corresponding to MainActivity.
use interface to communicate with activity from non activity class. create colorChange() in interface and get the instance of interface in non activity class and call that method.
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();
}
use this,
invalidateOptionsMenu ();
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