Search code examples
androidandroid-fragmentsfragmentandroid-fragmentactivityandroid-menu

FragmentActivity Action Bar Options Menu


I'm trying to add ActionBar buttons to a FragmentActivity and I can't figure out what I'm doing wrong. When running the app all I see is the default menu button on the ActionBar and not my button..

The FragmentActivity :

   @Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.animalsmenu,menu);
    return true;
}

The xml file:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/dogs"
    android:title="Dogs"
    android:orderInCategory="1"
    app:showAsAction="always">
</item>


Solution

  • The FragmentActivity class extends (derives from) the Activity class. The documentation for the Activity onCreateOptionsMenu(Menu menu) method states the following...

    The default implementation populates the menu with standard system menu items. These are placed in the CATEGORY_SYSTEM group so that they will be correctly ordered with application-defined menu items. Deriving classes should always call through to the base implementation.

    In other words, change your code to...

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.animalsmenu, menu);
        super.onCreateOptionsMenu(menu);
        return true;
    }
    

    This will inflate your menu item into the Menu passed in to your overridden method and then you pass it to the parent (super) version of the method.