关于RecyclerView notifyItemChanged() 刷新下标错误问题

来源:互联网 发布:淘宝图片盾在哪里设置 编辑:程序博客网 时间:2024/05/22 02:58

今天在项目调用RecyclerView adapter刷新数据时,用到了notifyItemChanged()方法,此方法是更新指定item数据,结果没想到弄了半天发现总是刷新不对,打印Log日志一看,发现刷新的返回的position为1,当时真是莫名其秒明明传的是对应的position为什么 adapter里返回的总是不对,后面经过看notifyItemChanged()方法的源码得知具体如下:


/** * Notify any registered observers that the item at <code>position</code> has changed. * Equivalent to calling <code>notifyItemChanged(position, null);</code>. * * <p>This is an item change event, not a structural change event. It indicates that any * reflection of the data at <code>position</code> is out of date and should be updated. * The item at <code>position</code> retains the same identity.</p> * * @param position Position of the item that has changed * * @see #notifyItemRangeChanged(int, int) */public final void notifyItemChanged(int position) {    mObservable.notifyItemRangeChanged(position, 1);}
源码中得知notifyItemChanged最终调用的是notifyItemRangeChanged(),这里有2个参数,第一个简单就是你要刷新的下标,但是第二个参数一般人不理解,其实从字面上的意思可知它要传的是你item的总count数,我之前没传这里itemCount默认就为1,所以不管你传什么这里返回的就是下标为1的item,明白了这一层解决起来就很容易了,我们只需把第二个参数也改为position就可以了或者传入itemCount总数也行~

0 0
原创粉丝点击