Question

Assume we have a activity which is a child class of an activity defined in a library. In this child class, we want to add additional menu item into the menu created by the base class. But we want this additional menu item defined in XML. Is that possible? How?

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    // TODO: how to add an additional menu item here?
    // the item is defined in xml
    // the id is item_switch_browsing_mode
    return true;
}

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/item_switch_browsing_mode"
        android:icon="@android:drawable/ic_menu_view"
        android:showAsAction="always"/>
</menu>
Was it helpful?

Solution

Try menu inflater, it should add menu items based on the specified xml, but call super.onCreateOptionsMenu to populate the parent menu items first. Something like this:

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

You may refer to http://developer.android.com/reference/android/view/MenuInflater.html.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top