今天使用RecyclerView時,上下兩個RecyclerView,在實現下拉刷新時,報錯:
java.lang.IndexOutOfBoundsException: Inconsistency detected.
Invalid view holder adapter positionViewHolder{56798b2 position=2 id=-1, oldPos=2, pLpos:-1 scrap [attachedScrap] tmpDetached no parent}
在網上看到這個方法可以暫時性解決問題
其實也不是什么解決方法,只是把這個異常捕獲了,不讓他奔潰了,這個問題的終極解決方案還是得讓google去修復。
1、創建一個類LinearLayoutManagerWrapper繼承LinearLayoutManager,重寫onLayoutChildren方法
- public class WrapContentLinearLayoutManager extends LinearLayoutManager {
- public WrapContentLinearLayoutManager(Context context) {
- super(context);
- }
- public WrapContentLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
- super(context, orientation, reverseLayout);
- }
- public WrapContentLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
- super(context, attrs, defStyleAttr, defStyleRes);
- }
- @Override
- public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
- try {
- super.onLayoutChildren(recycler, state);
- } catch (IndexOutOfBoundsException e) {
- e.printStackTrace();
- }
- }
- }
2、設置RecyclerView的布局管理為WrapContentLinearLayoutManager對象
- mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));