这个选择模式切换看起来真的很尴尬,因为我没有可以谷歌搜索的干净简单的解决方案。HFM(有信仰的人)和 KISS(保持简单愚蠢)有帮助;)
1.以单一模式选择开始并设置所有侦听器(这是在您设置列表适配器的地方完成的)
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemLongClickListener(liListener);
listView.setMultiChoiceModeListener(mcListener);
2.实现界面切换选择模式。使它起作用的技巧是在实现之外切换回单选模式,这意味着在您破坏动作模式之后!所以只需使用一个简单的标志来标记 CAB 的破坏。另一个 TRICK 是返回 false onItemLongClick 以便选择模式有时间生效。
private OnItemLongClickListener liListener = new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
isCABDestroyed = false;
return false; // so this action does not consume the event!!!
}
};
private MultiChoiceModeListener mcListener = new MultiChoiceModeListener() {
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
final int checkedCount = listView.getCheckedItemCount();
switch (checkedCount) {
case 0:
mode.setSubtitle(null);
break;
case 1:
mode.setSubtitle("One item selected");
break;
default:
mode.setSubtitle("" + checkedCount + " items selected");
break;
}
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
//do your action command here
mode.finish();
return true;
default:
return false;
}
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
isCABDestroyed = true; // mark readiness to switch back to SINGLE CHOICE after the CABis destroyed
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
};
3.这里是切换回来
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(isCABDestroyed) {
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//do your action command here
}
l.setItemChecked(position, true);
}