Question

Is it possible to inherit and extend XML resources in android easily, specifically for menus.

For example. if my base_menu.xml is

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:id="@+id/item_manual_input"
        android:title="@string/manual_input/">

    <item android:id="@+id/item_logoff"
        android:title="@string/logoff"/>

</menu>

Both options I'd like to reuse elsewhere (in another activity). instead of repeating the tags for the items in base_menu, I'd very much like to do something like this for inheriting_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <menu android:id="@id/base_menu"/>

    <item android:id="@+id/extra_option"
        android:title="@string/extra_option/>

</menu>

but I don't see anything similar to this in any documentation. Is anything like this supported, or am I stuck with using fragments to limit code and XML replication for various XML resources? (I believe this would work, but I haven't used fragments yet)

Was it helpful?

Solution

Not possible for menus but doable for layouts.
See include tag: https://developer.android.com/training/improving-layouts/reusing-layouts.html

For the menu:
You can work around in the code by inflating menu xml files and adding single menu items:

@Override public boolean onCreateOptionsMenu(Menu menu)
{
    getMenuInflater().inflate(R.menu.base, menu); // All menus in base.xml
    getMenuInflater().inflate(R.menu.extras, menu); // base.xml + extras.xml
    menu.add("More"); // base.xml + extras.xml + "More"
    return true;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top