RecyclerView checkBox状态问题

 

前言

最近碰到的问题,直接上图

解决方案

设置checkBox监听器为空及有个表来记录checkBox的状态
在@Override 的 onBindViewHolder方法里面这样写就行

   @Override
    public void onBindViewHolder(final RecyclerViewAdapter.ViewHoder holder, final int position)  {
        holder.cb.setOnCheckedChangeListener(null);
        holder.cb.setChecked(Beans.get(position).isCb());
        holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                Beans.get(position).setCb(b);
            }
        });
    }

关键代码是这个

 holder.cb.setOnCheckedChangeListener(null);
Beans.get(position).setCb(b);

cb是checkBox这就不用说了,Beans里面有个成员变量是用来储存chenkBox状态的(一般来说都是建个表来储存checkBox的值)

加上这2句之后

 

搞定,收工!!!

原因分析

recyclerView每次滑动加载内容是都会调用一次onBindViewHolder这个方法,
所以如果没有保存checkBox就会出现第一张图的情况。所以要在checkBox的监听器里保存下状态
而且在recyclerView里的,checkBox是复用状态的
所以每次使用都要清空下监听器,不然就会出问题

 holder.cb.setOnCheckedChangeListener(null);

 



作者:水天滑稽天照八野滑稽石
链接:https://www.jianshu.com/p/7188078e5bbf
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值