Reputation: 221
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>
Upvotes: 3
Views: 11124
Reputation: 1795
Make your MainActivity
extend ActionBarActivity
instead of FragmentActivity
.
ActionBarActivity
itself extends FragmentActivity
so you should be fine.
Upvotes: 12
Reputation: 48871
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.
Upvotes: 5
Reputation: 5591
From the Fragment Documents
public void setHasOptionsMenu (boolean hasMenu) Report that this fragment would like to participate in populating the options menu by receiving a call to onCreateOptionsMenu(Menu, MenuInflater) and related methods.
Hence you should call setHasOptionsMenu(true)
in your onCreate()
.
Or for backwards compatibility it's better to place this call as late as possible at the end of onCreate()
or even later in onActivityCreated()
.Try using this in either onCreate()
or onActivityCreated()
.
Hope this helps.
Upvotes: 2