1,在res 中新建一个menu文件夹
2,新建xml文件menu_item.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!--app:showAsAction="always" 显示图标-->
<item
android:id="@+id/action_call"
android:icon="@android:drawable/ic_menu_call"
app:showAsAction="always"
android:title="打电话" />
<item
android:id="@+id/action_camera"
android:icon="@android:drawable/ic_menu_camera"
android:title="照相" />
<item
android:id="@+id/action_add"
android:icon="@android:drawable/ic_menu_add"
android:title="添加" />
<item
android:id="@+id/action_delete"
android:icon="@android:drawable/ic_menu_delete"
android:title="删除" />
</menu>
3,重写public boolean onCreateOptionsMenu(Menu menu), public boolean onMenuOpened(int featureId, Menu menu)
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
//填充菜单
inflater.inflate(R.menu.menu_item, menu);
return super.onCreateOptionsMenu(menu);
}
/* 利用反射机制调用MenuBuilder的setOptionalIconsVisible方法设置mOptionalIconsVisible为true,给菜单设置图标时才可见
* 让菜单同时显示图标和文字
*/
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
if (menu != null) {
if (menu.getClass().getSimpleName().equalsIgnoreCase("MenuBuilder")) {
try {
Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
method.setAccessible(true);
method.invoke(menu, true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return super.onMenuOpened(featureId, menu);
}