所以我有一个GridView,我希望能够长按元素以启用上下文操作栏吗?我查了很多教程,包括https://www.bignerdranch.com/blog/recyclerview-part-2-choice-modes/和https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/view/List15.java,以及其他所有教程都说明当使用CHOICE_MODE_MULTIPLE_MODAL时,MultiChoiceModeListener应该在长按时自动使用
我看到许多教程使用它(就是这样)并且它可以工作,但是当我长时间按下我的GridView中的元素时,CAB无法启动(也没有调用onCreateActionView)我绝对无法弄清楚这是为什么。
这是我的GridView代码
receiptGridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
receiptGridView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
// int count = 0;
ArrayList<Receipt> tmp = new ArrayList();
@Override
public boolean onCreateActionMode(android.view.ActionMode actionMode, Menu menu) {
Log.d("DEBUG","Created action mode!");
MenuInflater inflater = actionMode.getMenuInflater();
inflater.inflate(R.menu.context_delete, menu);
return true;
}
@Override
public void onItemCheckedStateChanged(android.view.ActionMode actionMode, int i, long l, boolean b) {
receiptGridView.setSelection(i);
Receipt r = (Receipt) listAdapter.getItem(i);
if(b) {
tmp.add(r);
}
else {
tmp.remove(r);
}
actionMode.setTitle("Delete Items");
actionMode.setSubtitle(receiptGridView.getCheckedItemCount() + " items selected.");
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode actionMode, Menu menu) {
return true;
}
@Override
public boolean onActionItemClicked(android.view.ActionMode actionMode, MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_delete:
removeReceipts(tmp);
actionMode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
@Override
public void onDestroyActionMode(android.view.ActionMode actionMode) {
}
});
答案 0 :(得分:0)
原来实际触发操作菜单,你必须在gridview上调用setItemChecked,所以我只是在longpress上的容器视图中执行此操作
holder.container.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (ma.mActionMode == null) {
// the line that triggers it
ma.receiptGridView.setItemChecked(position, true);
v.setBackgroundResource(b ? R.color.color_ce5a5a : R.drawable.receipt_item_bg);
view.setBackgroundColor(Color.parseColor("#ce5a5a"));
}
return false;
}
});