Following will make things more clear:
1. onCreateOptionsMenu()
To specify the options menu for an activity,you override onCreateOptionsMenu()
. In this method, you can inflate your menu resource (defined in XML) into the Menu provided in the callback.
For Android 2.3.x and lower
, the system calls onCreateOptionsMenu()
to create the options menu when the user opens the menu for the first time. However for Android 3.0 and higher
, the system calls onCreateOptionsMenu()
when starting the activity, in order to show items to the action bar.
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.
2. onOptionsItemSelected()
When the you select an item from the options menu the system calls your activity's onOptionsItemSelected()
method. This method passes the MenuItem selected.
3. onPrepareOptionsMenu()
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.
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 invalidateOptionsMenu()
Refer this
For onPrepareOptionsMenu()
Refer this
Hence you can try as follows:
In order to deal with backward compatibility add following in your activity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Menu1:
refreshMenu();
break;
case R.id.Menu2:
refreshMenu();
break;
}
return super.onOptionsItemSelected(item);
}
public void refreshMenu() {
if (Build.VERSION.SDK_INT >= 11) {
invalidateOptionsMenu();
}
}
You can also refer this