How can I add an Action Bar Item during run time

hdoria picture hdoria · Apr 25, 2012 · Viewed 22.5k times · Source

How can I add an Action Bar Item during run time?

I am using actionBarSherlock, and I need to add some buttons when an event occurs (get some texts from a RSS, for example). I can't rely on a fixed xml.

Answer

Tony picture Tony · Apr 25, 2012

You can create the menu in code like this:

/*************************************/
/* Create the actionbar options menu */
/*************************************/
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    menu.add(0, 0, 0, "History").setIcon(R.drawable.ic_menu_recent_history)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    menu.add(0, 1, 0, "Settings").setIcon(R.drawable.ic_menu_manage)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

    return true;
}

Inside check for a boolean.

You will need to call supportInvalidateOptionsMenu() to recreate the menu.