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

来源:互联网 发布:淘宝网页布局工具 编辑:程序博客网 时间:2024/06/01 10:22

在 RecyclerView 中使用 CheckBox 时,滚动会导致CheckBox选中错乱而文字不会错乱?

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

1.创建一个全局集合(保存checkbox状态的)
// 先给其默认值为falseprivate 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);            }        });    }
原创粉丝点击