Sometimes need to change, add, delete options menu items dynamically after some event or after some situation in application flow.
We all know onCreateOptionsMenu method which helps to create options menu for activity. But in this situation it doesn’t help.
For this situation I use public boolean onPrepareOptionsMenu(Menu menu).
I will show short example which you can copy to your IDE and check my words.
Only one note for this method: don’t forget to clear menu items (menu.clear();) on every method start.
Example:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Class which shows how to change dynamically options menu items
* @author FaYnaSoft Labs
*/
public class Main extends Activity {
private Button clickBtn;
private boolean isChangedStat = false;
private static final int MENUITEM = Menu.FIRST;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
clickBtn = (Button) findViewById(R.id.click);
clickBtn.setText("Click me");
clickBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (isChangedStat) {
isChangedStat = false;
} else {
isChangedStat = true;
}
}
});
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if (isChangedStat) {
menu.add(0, MENUITEM, 0, "True");
} else {
menu.add(0, MENUITEM, 0, "False");
}
return super.onPrepareOptionsMenu(menu);
}
}
In this example I change after button click text in options menu item. It is very simple example. You can modify it for your problem. For example add, delete options menu items.
Why I recommended to clear menu? If you will not clear menu then after every click you will have plus one menu item.
Try to comment and you will see what I mean.
Hope this article was useful for you.
Don’t forget to grab our RSS feeds.

[...] Dynamically change Options Menu Items in Android The Developers Info. [...]
[Translate]
Thank you very much for making this work available.
It has helped me a lot and allowed me to progress with the project I am doing at the moment.
[Translate]