正如我在评论中所说,MenuItems
无法访问这些视图,因此您没有任何直接选项可以访问它们。为这些替换选择器的一种方法MenuItems
是使用MenuItems
设置ImageViews
为保存普通图标并更改那些选择器的操作视图ImageViews
。下面的一个例子:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menuFirst"
android:showAsAction="always"
android:actionLayout="@layout/image_menu_layout"/>
</menu>
<!-- image_menu_layout.xml -->
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
style="@style/Widget.ActionButton"/>
该ActionBar
部分的代码:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.your_menu, menu);
// call this for any menu item that you might have
setUpMenuItem(menu, R.id.menuFirst, false, null);
return super.onCreateOptionsMenu(menu);
}
/**
* This methods set up the MenuItems.
*
* @param menu the menu reference, this would refer either to the menu of the ActionBar or
* the menu of the ActionMode
* @param itemId the id of the MenuItem which needs work
* @param onActionMode flag to indicate if we're working on the ActionBar or ActionMode
* @param modeRef the ActionMode reference(only when the MenuItem belongs to the ActionMode,
* null otherwise)
*/
private void setUpMenuItem(Menu menu, int itemId, final boolean onActionMode,
final ActionMode modeRef) {
final MenuItem menuItem = menu.findItem(itemId);
ImageView itemLayout = (ImageView) menuItem.getActionView();
itemLayout.setBackgroundResource(onActionMode ? R.drawable.selector_for_actionmode : R
.drawable.selector_for_actionbar);
itemLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// for simplicity, wire up the normal selection callbacks(if possible,
// meaning the Activity implements the ActionMode.Callback)
if (onActionMode) {
onActionItemClicked(modeRef, menuItem);
} else {
onOptionsItemSelected(menuItem);
}
}
});
}
该ActionMode
部分的代码:
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
getMenuInflater().inflate(R.menu.actiomode_menu, menu);
// call this for any menu item that you might have
setUpMenuItem(menu, R.id.menu_item_from_actionmode, true, mode);
return true;
}
此方法还将允许您避免在使用 / 时处理/保持状态ActionBar
的ActionMode
需要Activity
。