Reputation: 151
I have a base class for my activities where I add the common action bar items.
public class BaseActivity extends ActionBarActivity
{
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return true;
In the activities where I extend my base activity I want to add some further items to the action bar.
public class ListActivity extends BaseActivity
{
@Override
public boolean onCreateOptionsMenu(Menu menu) {
addRefreshItemToMenu(menu);
return super.onCreateOptionsMenu(menu);
}
private void addRefreshItemToMenu(Menu menu) {
MenuItem refreshMenuItem = menu.add(R.string.menu_item_refresh);
refreshMenuItem.setIcon(R.drawable.ic_action_refresh);
refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
However MenuItem.setShowAsAction require API level 11, which is a problem since I use minSdkVersion="8".
How can I make this work using AppCompat?
Upvotes: 0
Views: 142
Reputation: 17085
Create a separate menu xml for your ListActivity
with showAsAction="always"
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/action_refresh"
android:title="@string/menu_item_refresh"
android:icon="@drawable/ic_launcher"
android:orderInCategory="100"
app:showAsAction="always" />
</menu>
And, inflate this menu on your ListActivity
which extends the BaseActivity
.
@Override
public boolean onCreateOptionsMenu(Menu menu){
// menu only for this Activity
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
// all other menus in BaseActivity will be added
return super.onCreateOptionsMenu(menu);
}
This will make sure you have the new menu only for this Activity and the common menus in the BaseActivity
Upvotes: 1
Reputation: 7793
You must use MenuItemCompat, because MenuItem.SHOW_AS_ACTION_ALWAYS appear only in API 11.
Upvotes: 1