RecycleView中使用RadioButton和CheckBox刷新报错

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

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

就是它

百度看了一下,有人说:

@川峰
因为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);
                }
            });

看出什么区别了吗?

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

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  
  if (!buttonView.isPressed()) {
       return;
  }
   /**----**/             
 }

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

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

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

欢迎收藏 Felix的Android笔记

持续更新

猜你喜欢

转载自blog.csdn.net/qq_39457683/article/details/123590970