android: changing option menu items programmatically
For anyone needs to change the options of the menu dynamically:
private Menu menu;
// ...
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
this.menu = menu;
getMenuInflater().inflate(R.menu.options, menu);
return true;
}
// ...
private void hideOption(int id)
{
MenuItem item = menu.findItem(id);
item.setVisible(false);
}
private void showOption(int id)
{
MenuItem item = menu.findItem(id);
item.setVisible(true);
}
private void setOptionTitle(int id, String title)
{
MenuItem item = menu.findItem(id);
item.setTitle(title);
}
private void setOptionIcon(int id, int iconRes)
{
MenuItem item = menu.findItem(id);
item.setIcon(iconRes);
}
menu.xml
<item
android:id="@+id/item1"
android:title="your Item">
</item>
put in your java file
public void onPrepareOptionsMenu(Menu menu) {
menu.removeItem(R.id.item1);
}