android: changing option menu items programmatically

Farhan  picture Farhan · Aug 20, 2011 · Viewed 111.5k times · Source

Is it possible to change the option menu items programmatically? Can anyone provide me with an example please?

Also, I want to disable certain items, so that they don't listen to the clicks, is it possible?

Answer

Eng.Fouad picture Eng.Fouad · Jul 28, 2012

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