FragmentActivity Activity Bar Options Menu

I am trying to add ActionBar buttons to FragmentActivity and I cannot figure out what I am doing wrong. When starting the application, all I see is the default menu button on the ActionBar, not my button.

FragmentActivity:

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

      

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>

      

+3


source to share


3 answers


The class FragmentActivity

extends (infers) the class Activity

. The documentation for Activity

the onCreateOptionsMenu method (menu) states the following ...

The default implementation populates the menu with standard system menu items. They are placed in the CATEGORY_SYSTEM group so that they are correctly ordered using specific menu items. Producer classes should always refer to the underlying 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 in Menu

passed to your overridden method and then pass it to the parent version ( super

) of the method.

+5


source


Do MainActivity

ActionBarActivity

ActionBarActivity

instead FragmentActivity

.



ActionBarActivity

it expands itself FragmentActivity

, so you should be fine.

+13


source


From Document Fragment

public void setHasOptionsMenu (boolean hasMenu) Communicate that this snippet would like to participate in populating the options menu by receiving a call to onCreateOptionsMenu (Menu, MenuInflater) and its associated methods.

Hence, you must call setHasOptionsMenu(true)

in onCreate()

.

Or, for backward compatibility, it is better to place this call as long as possible at the end onCreate()

or even later in onActivityCreated()

. Try using this in onCreate()

or onActivityCreated()

.

Hope it helps.

+2


source







All Articles