美文网首页
Cannot call this method while Re

Cannot call this method while Re

作者: 春生_7291 | 来源:发表于2019-08-26 20:14 被阅读0次
问题重现

RecylcerView不停的上拉加载更多 更新数据时(adapter执行notifyDataSetChanged)时出现java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling android.support.v7.widget.RecyclerView

字面意思:当Recyclerview计算布局或滚动时,不能调用此方法

解决方法

因此解决方案就是在更新数据时多加一层判断,在没有计算布局 且没有滚动时才能调用此方法进行数据更新。

首先先了解一下RecyclerView.getScrollState() 的枚举值有三个:

    //停止滚动
    public static final int SCROLL_STATE_IDLE = 0;
    
    //正在被外部拖拽,一般为用户正在用手指滚动
    public static final int SCROLL_STATE_DRAGGING = 1;
    
    //自动滚动开始
    public static final int SCROLL_STATE_SETTLING = 2;
    
方法1
private void bindListData(final List<DataBean> data) {
        LogUtil.e("recyclerView.getScrollState() :" + recyclerView.getScrollState() );//0 , 1
        LogUtil.e("recyclerView.isComputingLayout() :" + recyclerView.isComputingLayout());//false

        //没有计算布局 且没有滚动时
        if (recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_IDLE
                && (recyclerView.isComputingLayout() == false)) {
            //totalListBeanList.clear();
            totalListBeanList.addAll(data);
            dataAdapter.setData(totalListBeanList);
            dataAdapter.notifyDataSetChanged();
        }else {
            totalListBeanList.addAll(data);
        }
    }
方法2 (方法1的逆否)
private void bindListData(final List<DataBean> data) {
     
        //计算布局 或 滚动时
        if(recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE 
           ||  (recyclerView.isComputingLayout() == true)){
            totalListBeanList.addAll(data);
        }else {
            //totalListBeanList.clear();
            totalListBeanList.addAll(data);
            dataAdapter.setData(totalListBeanList);
            dataAdapter.notifyDataSetChanged();
        }
    }

参考:
Cannot call this method while RecyclerView is computing a layout or scrolling android.support.v7.wid

相关文章

网友评论

      本文标题:Cannot call this method while Re

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