One simple solution is to create OnItemCheckLister
, and implement it similar to following:
public class MyAdapter extends RecyclerViewAdapter {
interface OnItemCheckListener {
void onItemCheck(Item item);
void onItemUncheck(Item item);
}
...
@NonNull
private OnItemCheckListener onItemClick;
public MyAdapter (List<Item> items, @NonNull OnItemCheckListener onItemCheckListener) {
this.items = items;
this.onItemClick = onItemCheckListener;
}
...
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (holder instanceof MyViewHolder) {
final Item currentItem = items.get(position);
...
((MyViewHolder) holder).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((MyViewHolder) holder).checkbox.setChecked(
!((MyViewHolder) holder).checkbox.isChecked());
if (((MyViewHolder) holder).checkbox.isChecked()) {
onItemClick.onItemCheck(currentItem);
} else {
onItemClick.onItemUncheck(currentItem);
}
}
});
}
}
static class MyViewHolder extends RecyclerView.ViewHolder {
CheckBox checkbox;
View itemView;
...
public MyViewHolder(View itemView) {
super(itemView);
this.itemView = itemView;
checkbox = (CheckBox) itemView.findViewById(R.id.checkbox);
checkbox.setClickable(false);
...
}
public void setOnClickListener(View.OnClickListener onClickListener) {
itemView.setOnClickListener(onClickListener);
}
}
}
Then in the activity, we can do this:
private List<Item> currentSelectedItems = new ArrayList<>();
...
myAdapter = new MyAdapter(items, new MyAdapter.OnItemCheckListener() {
@Override
public void onItemCheck(Item item) {
currentSelectedItems.add(item);
}
@Override
public void onItemUncheck(Item item) {
currentSelectedItems.remove(item);
}
});
Then you can do stuff with currentSelectedItems
.
Note: Since this solution suppose for the whole Item to be pressed so the checkbox is set to be not clickable.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…