• RecyclerView 数据更新方法 notifyItemChanged/notifyItemInsert/notifyIteRemoved


    RecyclerView 数据更新方法 notifyItemChanged/notifyItemInsert/notifyIteRemoved

    notifyItemInserted

    java.lang.IndexOutOfBoundsException: 
    Inconsistency detected. Invalid view holder adapter positionViewHolder{424b7690 position=7 id=-1, oldPos=8,pLpos:8 scrap tmpDetached no parent} at 
    android.support.v7.widget.RecyclerView$Recycler.validat
    eViewHolderForOffsetPosition(RecyclerView.java:4349)
    
    • 1
    • 2
    • 3
    • 4

    工作中遇到如下问题 notifyItemInserted(list.size()-1),一个一个的插入也没什么问题,但是快速连续插入的话就会报出IndexOutOfBoundExcetion的异常,然后崩溃。经过多方查找,翻阅Android 的相关文档,发现如下解决方法。

    使用notifyItemInserted方法向末尾处添加item的时候,要使用如下的方式

    notifyItemInserted(list.size());

    其中list.size()才能正确的计算出插入的位置,然后在调用

    notifyItemChanged(list.size());

    notifyItemRemoved

    使用 notifyItemRemoved方法删除时,需要使用getLayoutPosition计算位置
    否则也会报出IndexOutOfBoundExcetion异常,同时使用notifyItemChanged(removePos);方法刷新一下

    notifyItemChanged

    事实上RecyclerView的notifyItemChanged的底层调用的是notifyItemRangeChanged:

     /**
             * Notify any registered observers that the item at position has changed.
             * Equivalent to calling notifyItemChanged(position, null);.
             *
             * 

    This is an item change event, not a structural change event. It indicates that any * reflection of the data at position is out of date and should be updated. * The item at position retains the same identity.

    * * @param position Position of the item that has changed * * @see #notifyItemRangeChanged(int, int) */ public final void notifyItemChanged(int position) { mObservable.notifyItemRangeChanged(position, 1); }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    该方法使得RecyclerView批量范围内(range)数据更新,notifyItemChanged巧妙的将第二个参数计数器设置为1得以实现。

  • 相关阅读:
    Vulnhub: Masashi: 1靶机
    不完全解构和剩余运算符
    建筑类企业做ISO9001时需要带GB/T50430标准
    mmpose关键点(二):构建自己的训练集
    算法的基本概念
    树的统计问题
    linux下golang环境配置问题记录
    人工智能-线性神经网络
    生活笔记——嵌入式人工智能小记(2022_8_7)
    SE (Squeeze Excitation)模块
  • 原文地址:https://blog.csdn.net/hnjzfwy/article/details/133892961