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

在项目中使用RecyclerView的notifyItemChanged()方法更新指定item时遇到问题,发现实际刷新的位置与传入的位置不匹配。通过查看源码了解到问题所在,详细解释了这一现象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在项目调用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总数也行~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值