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.
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With