在做一块嵌套CheckBox的recyclerview,并且包含增删功能的时候,滑动列表的时候,选中项出现错位,通过给CheckBox设置tag,防止CheckBox选中或取消选中的时候触发事件
CheckBox checkBox = (CheckBox) holder.getView(R.id.checkBox);
checkBox.setTag(new Integer(item.getDevice_id()));
if (posList != null) {
checkBox.setChecked(posList.contains(new Integer(item.getDevice_id())));
} else {
checkBox.setChecked(false);
}
onchecked(checkBox,holder,position, item.getDevice_id());
Device_id是唯一的可以用来作为tag,也可以用其他的唯一的不变的属性作为tag,下面是 onchecked方法
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
if (!posList.contains(checkBox.getTag())) {
choiceDevice.add(deviceList.get(position));
posList.add(new Integer(device_id));
}
} else {
if (posList.contains(checkBox.getTag())) {
choiceDevice.remove(deviceList.get(position));
posList.remove(new Integer(device_id));
}
}
}
});
在点击的时候判断tag来决定选中或者取消