正如adneal的评论中所建议的那样
我有一个listActivity,它在长时间单击时显示CAB。如果选择了一个以上的菜单项,我想隐藏其中一个菜单项。
我跟踪onItemCheckedStateChanged()
中选择的项目数。但是,我无法访问菜单以从此功能中删除该项目。请参阅下面代码中的注释,了解我正在尝试的内容。我觉得我错过了一些简单的核心理解。。。下面的代码是从我的onCreate()
函数中调用的。
private void setupActionBarContext() {
ListView listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
private int selCount = 0;
ArrayList<Long> idList = new ArrayList<Long>();
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
if (checked) {
selCount++;
idList.add(id);
} else {
selCount--;
idList.remove(id);
}
mode.setTitle(selCount + " selected");
// I WOULD LIKE TO HIDE ITEM ON MENU IF 'selCount' IS > 1
// For example something like this...
// if (selCount > 1) {
// MenuItem item = menu.findItem(R.id.edit_item);
// item.setVisible(false);
// } else {
// MenuItem item = menu.findItem(R.id.edit_item);
// item.setVisible(false);
// }
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete_item:
for(Long i: idList){
mDbHelper.deleteItem(i);
}
mode.finish();
return true;
case R.id.edit_item:
Toast.makeText(getBaseContext(), "Edit Item", Toast.LENGTH_SHORT).show();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate the menu for the CAB
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
selCount = 0;
idList.clear();
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
});
还有我的菜单项。。。
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/edit_item"
android:title="@string/edit_item"
android:showAsAction="ifRoom"
android:orderInCategory="1"/>
<item android:id="@+id/delete_item"
android:title="@string/delete_item"
android:icon="@drawable/ic_action_delete"
android:showAsAction="ifRoom"
android:orderInCategory="2"/>
</menu>
将invalidate()添加到onItemCheckedStateChanged()
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
if (checked) {
selCount++;
idList.add(id);
} else {
selCount--;
idList.remove(id);
}
mode.setTitle(selCount + " selected");
mode.invalidate(); // Add this to Invalidate CAB
}
这将使CAB无效,并导致调用onPrepareActionMode()
函数。
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
if (selCount == 1){
MenuItem item = menu.findItem(R.id.edit_item);
item.setVisible(true);
return true;
} else {
MenuItem item = menu.findItem(R.id.edit_item);
item.setVisible(false);
return true;
}
}