Adding the Add button to the action bar at the top when you already have tabs and menus

I am trying to add the Add Item button at the top of the action bar. (To the right of the icon and application name).

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

I thought the actionbar also uses an XML menu. So I added an XML menu to the action menu, 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 will fail. I believe that I am doing this completely wrong.

My XML action bar:

<?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>

In some tutorials, I read that I have to add items to the action bar and populate them through the OnCreateOptionsMenu function in mainActivity. But where my options menu is populated, not my action bar.

+5
1

ActionBar onCreateOptionsMenu().

setcustomview() onCreateOptionsMenu

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

   return true;
} 

ActionBar, onOptionsItemSelected(). . , , , :

@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;
} 
+8

All Articles