• 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得以实现。

  • 相关阅读:
    openshift搭建Istio
    RabbitMq大纲
    github能够正常运行,但点击别人发的链接进行模型下载时访问不了该网页是什么问题?
    QT中启动窗口QSplashScreen的使用
    atguigu----kafka概述
    微信每日早安推送
    电子商务、搜索引擎
    java设计模式---责任链模式详解
    Java中运算符一些注意事项
    Proxmox VE Install 7.2
  • 原文地址:https://blog.csdn.net/hnjzfwy/article/details/133892961