RecyclerView快速滑动到顶部刷新,清空数据报Inconsistency detected异常

RecyclerView快速滑动到顶部刷新,报Inconsistency detected异常。

解决方法1:重写LayoutManger的supportsPredictiveItemAnimations()方法,return false;(经过本人尝试,下拉刷新的时候清空数据集合,获取数据后使用notifyDataSetChanged()方法,下拉刷新的一瞬间快速上滑动还是可能会发生这种错误)

I had a (possibly) related issue - entering a new instance of an activity with a RecyclerView, but with a smaller adapter was triggering this crash for me.

RecyclerView.dispatchLayout()can try to pull items from the scrap before calling mRecycler.clearOldPositions(). The consequence being, is that it was pulling items from the common pool that had positions heigher than the adapter size.

Fortunately, it only does this if PredictiveAnimations are enabled, so my solution was to subclass GridLayoutManager (LinearLayoutManager has the same problem and 'fix'), and override supportsPredictiveItemAnimations() to return false :

/** * No Predictive Animations GridLayoutManager */
private static class NpaGridLayoutManager extends GridLayoutManager { 
/** 
  * Disable predictive animations. There is a bug in RecyclerView which causes views that * are being reloaded to pull invalid ViewHolders from the internal recycler stack if the 
  * adapter size has decreased since the ViewHolder was recycled. 
  */ 
    @Override 
    public boolean supportsPredictiveItemAnimations() { 
        return false;
   } 
    public NpaGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 
        super(context, attrs, defStyleAttr, defStyleRes); 
    } 
    public NpaGridLayoutManager(Context context, int spanCount) {   
        super(context, spanCount); 
    } 
    public NpaGridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) { 
        super(context, spanCount, orientation, reverseLayout); 
    }
}

解决方法2:不使用notifyDataSetChanged()方法更新数据,刷新的时候使用RecyclerView 的notifyItemRangeRemoved()方法移除数据,后取到数据的时候使用notifyItemRangeInserted()方法添加数据

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,558评论 25 708
  • 简介: 提供一个让有限的窗口变成一个大数据集的灵活视图。 术语表: Adapter:RecyclerView的子类...
    酷泡泡阅读 5,218评论 0 16
  • 曼曼冰冰阅读 176评论 1 0
  • GCD是异步执行任务的技术支之一,开发者只需要将想要执行的block任务添加到适当的Dispatch Queue(...
    zziazm阅读 1,778评论 0 8
  • 今年我二十三岁 我不会哭,也不想笑 现实给了我一巴掌 小伙子,穷逼不要谈梦想与远方 我骑着小黄车 在大马路上 羡慕...
    无年shadow阅读 314评论 2 2