1. 程式人生 > >RecyclerView-錯誤收集:當你重新整理RecyclerView程式崩掉的時候(1)

RecyclerView-錯誤收集:當你重新整理RecyclerView程式崩掉的時候(1)

報錯資訊

摸著後腦勺,一臉懵逼地看著Android Studio列印著下面這段日誌:

 java.lang.IllegalArgumentException: Scrapped or attached views may not be recycled. isScrap:false isAttached:true
                      at android.support.v7.widget.RecyclerView$Recycler.recycleViewHolderInternal(RecyclerView.java:5420)
                      at android.support
.v7.widget.RecyclerView$Recycler.quickRecycleScrapView(RecyclerView.java:5506) at android.support.v7.widget.RecyclerView$LayoutManager.removeAndRecycleScrapInt(RecyclerView.java:8023) at android.support.v7.widget.RecyclerView.dispatchLayoutStep3(RecyclerView.java
:3447) at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3194) at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3627) at android.view.View.layout(View.java:16009) at android.view
.ViewGroup.layout(ViewGroup.java:5181) at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1195) at android.view.View.layout(View.java:16009) at android.view.ViewGroup.layout(ViewGroup.java:5181) at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1795) at android.view.View.layout(View.java:16009) at android.view.ViewGroup.layout(ViewGroup.java:5181) at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:131) at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42) at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1367) at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:849)

後來百度發現原因是:
onRefresh方法裡的資料清空應該放在請求資料成功後再清空!

 mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                contents.clear();
                current_page = 1;
                netData(current_page + "");
                mRecyclerView.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                current_page++;
                netData(current_page + "");
                mRecyclerView.loadMoreComplete();
            }
        });

其解決方法是:
將列表清空的方法放到獲取到介面資料以後執行。

 @Override
                    protected void requestBody(List<BillListEntity> data) {
                            promptDialog.dismissImmediately();
                        if (contents.size() != 0 && "1".equals(current_page) ) {//剔除重複載入第一頁
                            contents.clear();
                        }