1. 程式人生 > >RecycleView異常Added View has RecyclerView as parent but view is not a real child. Unfiltered index:0

RecycleView異常Added View has RecyclerView as parent but view is not a real child. Unfiltered index:0

Android RecycleView  異常 

java.lang.IllegalStateException:Added View has RecyclerView as parent but view is not a real child. Unfiltered index:0

log日誌:

07-16 14:54:12.075: E/AndroidRuntime(20475): java.lang.IllegalStateException:
Added View has RecyclerView as parent but view is not a real child. Unfiltered
index:0
07-16 14:54:12.075: E/AndroidRuntime(20475):     at
android.support.v7.widget.RecyclerView$LayoutManager.addViewInt(RecyclerView.java:6720)
07-16 14:54:12.075: E/AndroidRuntime(20475):     at
android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:6686)
07-16 14:54:12.075: E/AndroidRuntime(20475):     at
android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:6674)


在使用RecycleView中 偶爾出現了該異常 

追蹤該異常發現出自

android.support.v7.widget.RecyclerView$LayoutManager.addViewInt(RecyclerView.java:6720)
if (child.getParent() == mRecyclerView) { // it was not a scrap but a valid child
                // ensure in correct position
                int currentIndex = mChildHelper.indexOfChild(child);
                if (index == -1) {
                    index = mChildHelper.getChildCount();
                }
                if (currentIndex == -1) {
                    throw new IllegalStateException("Added View has RecyclerView as parent but"
                            + " view is not a real child. Unfiltered index:"
                            + mRecyclerView.indexOfChild(child));
                }
                if (currentIndex != index) {
                    mRecyclerView.mLayout.moveView(currentIndex, index);
                }
            }

發現異常原因是  :

recycleView同時進行 "下拉重新整理" 和 "載入更多" 而產生衝突   .

recycleView  執行非同步的"載入更多"操作後 , 當呼叫recycleView   的addviewInt方法填充資料時,   發現列表已經被"下拉重新整理"刪除了. 找不到常規的child.

解決異常:

禁止 RecycleView  "下拉重新整理" 和 "載入更多"  同時執行  . 

同一時間只允許使用者使用一種動作 (即: 重新整理不載入  載入不重新整理 )

//  ┏┓   ┏┓
//┏┛┻━━━┛┻┓
//┃       ┃
//┃   ━   ┃
//┃ ┳┛ ┗┳ ┃
//┃       ┃
//┃   ┻   ┃
//┃       ┃
//┗━┓   ┏━┛
//   ┃   ┃   神獸保佑
//   ┃   ┃   程式碼無BUG!
//   ┃   ┗━━━┓
//   ┃       ┣┓
//   ┃       ┏┛
//   ┗┓┓┏━┳┓┏┛
//     ┃┫┫ ┃┫┫
//     ┗┻┛ ┗┻┛

謝謝