Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a 'Add Button' to the actionbar at the top when you already have tabs and a menu

I'm trying to add an 'Add Item' button at the top in the action bar. (To the right of the App Icon and Title).

Right under the action bar, I have two tabs that I can swipe between. I also have a menu XML file defined for the settings menu.

I thought actionbar uses a menu XML as well. So I added a actionbar menu XML, but when I use

actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);
actionbar.setCustomView(R.menu.actionbar);

my program crashes. I believe I'm doing this totally incorrectly.

My actionbar XML:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/item1" android:icon="@android:drawable/ic_menu_add"></item>


</menu>

I read on some tutorials that I'm supposed to add items to the actionbar and populate it via the OnCreateOptionsMenu function in mainActivity. But that's where my options menu is populated, not my actionbar.

like image 710
CREW Avatar asked Apr 13 '13 21:04

CREW


1 Answers

An activity populates the ActionBar in its onCreateOptionsMenu() method.

Instead of using setcustomview(), just override onCreateOptionsMenu like this

@Override
public boolean onCreateOptionsMenu(Menu menu){
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);

   return true;
} 

If an actions in the ActionBar is selected, the onOptionsItemSelected() method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menuitem1:
           Toast.makeText(this,"Menu Item 1 selected",Toast.LENGTH_SHORT).show();
           break;
        case R.id.menuitem2:
           Toast.makeText(this,"Menu item 2 selected",Toast.LENGTH_SHORT).show();
           break;
        default:
           break;
    }

    return true;
} 
like image 168
Buneme Kyakilika Avatar answered Nov 13 '22 00:11

Buneme Kyakilika