RecyclerView自带bug,切换数据出现IndexOutOfBoundsException

来源:互联网 发布:全聚合网络电视电脑版 编辑:程序博客网 时间:2024/06/01 18:55

今天在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方法,算是暂时解决了问题,没再崩溃,但是这个仅仅只是治标之法,治本还得靠谷歌修复一下。

阅读全文
0 0
原创粉丝点击