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

在 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);
            }
        });
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值