How to include a common menu item in multiple menus in Android menu xml?

99封情书 提交于 2019-12-28 16:31:06

问题


Many of menus have always one item same to all.

Is there the way to define that item as extra menu and include it to all other?

Something like this:

menu/main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_main"
          android:title="@string/text_mainmenu" />
</menu>

menu/other.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      parent="@menu/main">
    <item android:id="@+id/menu_other"
          android:title="@string/text_othermenu" />
</menu>

I know, that it's possible to do it programmaticaly, but I thought xml-way is nicer.


回答1:


AFAIK, <include> only works for layout XML, not menu XML, though you can certainly give it a try. Lacking that, the programmatic option (inflating both menu XML files) is the only option I am aware of.




回答2:


Inflating each menu and calling to super works great! Here is an example:

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

You can control the order if super also adds more items by calling it before/after other inflates, or not call at all it to ignore those items.



来源:https://stackoverflow.com/questions/4337034/how-to-include-a-common-menu-item-in-multiple-menus-in-android-menu-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!