android 根据code选中 recyclerView adapter内的某一条CheckBox数据
可以通过以下步骤在 RecyclerView Adapter 内选中某一条 CheckBox 数据:
- 在 Adapter 中定义一个 HashMap,用于记录哪些 CheckBox 被选中了:
private HashMap<Integer, Boolean> checkedHashMap = new HashMap<>();
- 在 Adapter 的构造函数中初始化 HashMap,并将所有 CheckBox 的初始状态设置为未选中:
public MyAdapter(List<MyData> dataList) {
this.dataList = dataList;
for (int i = 0; i < dataList.size(); i++) {
checkedHashMap.put(i, false);
}
}
- 在 onBindViewHolder 方法中设置 CheckBox 的状态:
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// 设置 CheckBox 状态
holder.checkBox.setChecked(checkedHashMap.get(position));
}
- 在 CheckBox 的 OnCheckedChangeListener 中更新 HashMap 中对应的值:
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkedHashMap.put(position, isChecked);
}
});
- 在外部调用 RecyclerView.Adapter 的 notifyItemChanged 方法,通知 Adapter 刷新对应位置的数据:
// 根据 code 查找对应的 position
int position = -1;
for (int i = 0; i < dataList.size(); i++) {
if (dataList.get(i).getCode().equals(code)) {
position = i;
break;
}
}
// 如果找到了对应的 position,更新 HashMap 中对应的值,并刷新 RecyclerView
if (position >= 0) {
checkedHashMap.put(position, true);
notifyItemChanged(position);
}
``
原文地址: https://www.cveoy.top/t/topic/egDC 著作权归作者所有。请勿转载和采集!