add actionbar button with navigation drawer?

10,228

Solution 1

In your Activity_Main, or whatever is your main activity, you call:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.YOUR_MENU, menu);
    super.onCreateOptionsMenu(menu,inflater);
}

YOUR_MENU is the options menu/actionbar you want.

If you want to add another button, or individualize the buttons according to the specific fragment inside the frame_layout/drawer layout, then in your fragment, put add this in the onCreateView:

setHasOptionsMenu(true);

This tells the activity that you are going to alter the options menu.

Then:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.YOUR_NEW_MENU, menu);
    super.onCreateOptionsMenu(menu,inflater);
}

Whatever items YOUR_NEW_MENU has will be added to the optionsmenu/actionbar.

Solution 2

Did you map this Menu Item to your activity? If not you need to override onCreateOptionsMenu in your activity and inflate it there.

You can read this tutorial on menus.

Share:
10,228
jscherman
Author by

jscherman

Updated on June 06, 2022

Comments

  • jscherman
    jscherman almost 2 years

    i am having this problem: i'm working with the actionbar navigation drawer, but i want to add aditionally a button to the menu bar, something like these buttons: http://screenshots.en.sftcdn.net/blog/en/2013/06/notifications-b.png

    this is my xml file:

    <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/drawer_layout"
     android:layout_width="match_parent"
     android:layout_height="match_parent" >
    
    <FrameLayout
         android:id="@+id/content_frame"
         android:layout_width="match_parent"
         android:layout_height="match_parent" />
         <!-- The navigation drawer -->
    <ListView
         android:id="@+id/left_drawer"
         android:layout_width="240dp"
         android:layout_height="match_parent"
         android:layout_gravity="start"
         android:background="#111"
         android:choiceMode="singleChoice"
         android:divider="@android:color/transparent"
         android:dividerHeight="0dp" />
    </android.support.v4.widget.DrawerLayout>
    

    so, i know that adding a buttons is something like this:

    <menu xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
        <!-- Search, should appear as action button -->
        <item android:id="@+id/action_search"
              android:icon="@drawable/ic_action_search"
              android:title="@string/action_search"
              yourapp:showAsAction="ifRoom"  />
    </menu>
    

    but i still don't know how to fit both parts, can anybody help me?