您的位置:首页 > 其它

RecyclerView复用的一些问题(Checkbox错乱)

2017-12-22 13:12 1216 查看
在 RecyclerView 中使用 CheckBox 时,滚动会导致CheckBox选中错乱而文字不会错乱?

因为文字是从数据源中拿出来的,而CheckBox的选中与否是没有数据源的,RecyclerView复用此item时,它会展示复用的item的所有属性,并根据数据源替换数据,既文字可以替换,而CheckBox继续沿用复用item的状态。

1.创建一个全局集合(保存checkbox状态的)


// 先给其默认值为false
private List<Boolean> booleans = new ArrayList<>();


2.onBindViewHolder()


@Override
public void onBindViewHolder(ViewHolder holder, final int position) {

CheckBox checkBox = holder.getView(R.id.rv_check_cb);

// 先设置一次CheckBox的选中监听器,传入参数null,防止多次监听错乱
checkBox.setOnCheckedChangeListener(null);
// 用集合中的值设置CheckBox的选中状态
checkBox.setChecked(booleans.get(position));
// 上面两步恢复了checkbox的状态,然后进行监听并更新checkbox状态
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

booleans.set(position,b);
}
});
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: