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

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

      • notifyItemInserted
      • notifyItemRemoved
      • notifyItemChanged

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)

工作中遇到如下问题 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); }

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

你可能感兴趣的:(学习交流,android,studio,java,算法,数据结构,kotlin)