当前位置:   article > 正文

RecycleView中使用RadioButton和CheckBox刷新报错_checkbox+recyclerview刷新

checkbox+recyclerview刷新

今天在做但单选列表时使用了RadioButton,就在最后快好了的时候出现报错!!!

IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling

  • 1
  • 2

就是它

百度看了一下,有人说:

@川峰
因为RecyclerView在计算layout的时候不允许你更新Adapter内容


@川峰
解决方法比较简单,既然RecyclerView已经给了判断方法了,那我们在onCheckedChanged方法中直接调用isComputingLayout()判断一下就可以了,如果该方法返回为true我们需要进行延时处理这里我直接调用RecyclerView对象的post方法或者你用Handler处理也可以。


ssnu 2021.09.14
个人认为问题根源在于只要有item处于checked状态setOnCheckedChangeListener里面的方法就会被循环调用,导至报错。用setOnClickListener可以节约资源。


养生程序yuan 2021.07.09
我的解决方案是Checkbox改为用onclicklistener,可以

当他们都提出是setOnCheckedChangeListener回调状态导致进入循环无限刷新时,我想到了我认为最佳的办法,解决办法如下:

RadioButton mRbButton = holder.getView(R.id.mRbButton);
            mRbButton.setText(str);
            mRbButton.setTextColor(Color.WHITE);
            mRbButton.setChecked(selectIndex == position);
            mRbButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (!buttonView.isPressed()) {
                        return;
                    }
                    int oldIndex = selectIndex;
                    selectIndex = position;
                    notifyItemChanged(oldIndex);
                    notifyItemChanged(position);
                }
            });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

看出什么区别了吗?

我在 onCheckedChanged(CompoundButton buttonView, boolean isChecked) 回调下加了

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  
  if (!buttonView.isPressed()) {
       return;
  }
   /**----**/             
 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

没错就是 buttonView.isPressed() 这样就判断是主动触发状态切换还是被动触发,完美解决onCheckedChanged无限回调问题

当然RadioButton状态切换报错也没有啦

有更好的办法或者疑问可以在下方留言

欢迎收藏 Felix的Android笔记

持续更新

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/733766
推荐阅读
相关标签
  

闽ICP备14008679号