RecyclerView自帶bug,切換資料出現IndexOutOfBoundsException
阿新 • • 發佈:2019-02-13
今天在APP在執行的時候,突然閃退了一下,檢視日誌看到了異常情況
看到java.lang.IndexOutOfBoundsException還以為是下標越界,檢查了一遍程式碼,沒發現什麼不合理的地方,於是又重新運行了一遍,重新按剛才操作來了一遍,再次出現這個異常,百度一番(不穀歌的原因眾所周知),才知道原來是RecyclerView自身的問題,谷歌一直沒修復,既然它沒改,那改的只有我們了,不能不用是不。
網上很多都是說重寫LinearLayoutManager方法,我也按照這個試了試,程式碼如下:
public class RecyclerViewBugLayoutManager extends LinearLayoutManager {
public RecyclerViewBugLayoutManager(Context context) {
super(context);
}
public RecyclerViewBugLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public RecyclerViewBugLayoutManager (Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
//把異常丟擲來,不至於程式崩潰
super.onLayoutChildren(recycler, state);
} catch (Exception e) {
e.printStackTrace();
}
}
}
這個方法雖然解決了大部分問題,但是如果是快速滑動點選切換資料的話還是會出現,於是我又在每次重新整理頁面之前clean資料之後先呼叫一下這個notifyDataSetChanged方法,算是暫時解決了問題,沒再崩潰,但是這個僅僅只是治標之法,治本還得靠谷歌修復一下。