Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an Action Bar Item during run time

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.

like image 982
hdoria Avatar asked Apr 25 '12 19:04

hdoria


People also ask

How do you add action items to the action bar?

All action buttons and other items available in the action overflow are defined in an XML menu resource. To add actions to the action bar, create a new XML file in your project's res/menu/ directory. The app:showAsAction attribute specifies whether the action should be shown as a button on the app bar.

How do I customize my action bar?

This example demonstrate about how to create a custom action bar in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How will you replace a menu with action bar in Android?

To replace an app's default action bar with a Toolbar : Create a new custom theme and modify the app's properties so that it uses this new theme. Disable the windowActionBar attribute in the custom theme and enable the windowNoTitle attribute. Define a layout for the Toolbar .


1 Answers

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.

like image 176
Tony Avatar answered Sep 24 '22 05:09

Tony