RecyclerView实现购物车的全选、反选功能
程序员文章站
2022-05-31 10:55:08
...
实现购物车的全选、反选功能
- 定义一个HasMap集合
private HashMap<Integer, Boolean> isCheckedHasMap;
- 把CheckBox与条目关联
isCheckedHasMap = new HashMap<>();
for (int i = 0; i < mData.size(); i++) {
isCheckedHasMap.put(i, false);
}
- CheckBox点击事件 添加在onBindViewHolder里面(cb是CheckBox的ID)
holder.cb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isCheckedHasMap.put(position, !isCheckedHasMap.get(position));
notifyDataSetChanged();
}
});
holder.cb.setChecked(isCheckedHasMap.get(position));
- 全选功能
public void selectedAll() {
Set<Map.Entry<Integer, Boolean>> entries = isCheckedHasMap.entrySet();
boolean shouldSelectedAll = false;
for (Map.Entry<Integer, Boolean> entryset : entries) {
Boolean aBoolean = entryset.getValue();
if (!aBoolean) {
shouldSelectedAll = true;
break;
}
}
for (Map.Entry<Integer, Boolean> entryset : entries) {
entryset.setValue(shouldSelectedAll);
}
notifyDataSetChanged();
}
- 反选功能
public void revertSelected() {
Set<Map.Entry<Integer, Boolean>> entries = isCheckedHasMap.entrySet();
for (Map.Entry<Integer, Boolean> entryset : entries) {
entryset.setValue(!entryset.getValue());
}
notifyDataSetChanged();
}