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

問題重現

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章