美文网首页
RecyclerView checkBox状态问题

RecyclerView checkBox状态问题

作者: 水天滑稽天照八野滑稽石 | 来源:发表于2018-07-26 17:22 被阅读0次

    前言

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

    解决方案

    设置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);
    

    相关文章

      网友评论

          本文标题:RecyclerView checkBox状态问题

          本文链接:https://www.haomeiwen.com/subject/hyibmftx.html