本文章是基于Android Samples——UI篇ActionBarCompat-Basic代码的学习笔记,代码的具体下载链接(需要翻墙下载)请撮我。
在ActionBar上添加menuItem的方式有两种。一种是在Menu的main.xml中添加item标签,另一种就是通过代码进行添加。
通过xml文件添加
这里在MainActivity中override的函数onCreateOptionsMenu中有指定menu的布局文件是main.xml,其位置位于res/menu目录下。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate our menu from the resources by using the menu inflater.
getMenuInflater().inflate(R.menu.main, menu);
......
}
因此,如需添加删除menu,menu的xml是一种方式。
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:support="http://schemas.android.com/apk/res-auto" >
<!--
Here we create an item, setting support:showAsAction to display the item as an action if
there's room on the compatible Action Bar.
-->
<item
android:id="@+id/menu_refresh"
android:icon="@drawable/ic_action_refresh"
android:title="@string/menu_refresh"
support:showAsAction="ifRoom"/>
<!-- Location item is added in onCreateOptionsMenu() -->
<!--
Here we set the settings item to always be in the overflow menu, by setting
support:showAsAction to never, so it is never displayed as an action item on the compatible
Action Bar.
-->
<item
android:id="@+id/menu_settings"
android:icon="@drawable/ic_action_settings"
android:title="@string/menu_settings"
support:showAsAction="never"/>
</menu>
通过代码添加
在Activity中onCreateOptionsMenu()中添加
// It is also possible add items here. Use a generated id from
// resources (ids.xml) to ensure that all menu ids are distinct.
MenuItem locationItem = menu.add(0, R.id.menu_location, 0, R.string.menu_location);
locationItem.setIcon(R.drawable.ic_action_location);
MenuItem showInfoItem = menu.add(0, R.id.menu_showinfo, 0, R.string.menu_showinfo);
showInfoItem.setIcon(R.drawable.ic_action_showinfo);
MenuItemCompat.setShowAsAction(showInfoItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
// Need to use MenuItemCompat methods to call any action item related methods
MenuItemCompat.setShowAsAction(locationItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
注意
- 代码中MenuItemCompat.setShowAsAction接口:
MenuItemCompat.setShowAsAction(locationItem, MenuItem.SHOW_AS_ACTION_IF_ROOM)
- menu的xml中item标签support:showAsAction属性。
<item
......
support:showAsAction="always"
/>
上面两种方式都是可以指定Menu Item的可见性,效果相同。
MenuItem | support:showAsAction | 备注 |
---|---|---|
SHOW_AS_ACTION_NEVER | never | |
SHOW_AS_ACTION_IF_ROOM | ifRoom | |
SHOW_AS_ACTION_ALWAYS | always | |
SHOW_AS_ACTION_WITH_TEXT | withText | |
SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | collapseActionView |