![](/img/trans.png)
[英]notifyItemChanged(int) does not update RecyclerView.Adapter
[英]RecyclerView.Adapter notifyItemChanged() with async network update?
我有一个使用LinearLayoutManager的RecyclerView和一个自定义的RecyclerView.Adapter。 当用户长按某个项目时,它会触发仅对该项目进行异步网络刷新。 我知道项目在长按时的位置,我可以将该位置传递给网络刷新功能。 但是,当刷新完成并且notifyItemChanged()
,用户可能已添加新项目或已删除项目。 因此,虽然刷新的项目可能源自位置4,但是在刷新完成时它可以在3或5或其他地方。
如何确保使用正确的位置参数调用notifyItemChanged()
?
这有三种可能的解决方案:
改为调用notifyDataSetChanged()
并将其调用一天。
通过适配器中的唯一ID保留单独的项目映射。 让网络刷新返回项目以及唯一ID。 通过ID地图访问该项目并找出其位置。 显然,如果您的商品没有唯一ID,则不能选择此选项。
跟踪正在刷新的商品。 注册您自己的AdapterDataObserver
并跟踪所有插入和更新,每次计算项目的新位置并保存直到刷新返回。
虽然notifyDataSetChanged()可以解决这个问题,但是如果知道项目的位置是必不可少的,那么你总是可以在recyclerview适配器中使用的列表项的模型类中实现hashCode和equals。
实现hashcode和equals方法以获取所需模型对象的位置。
示例:
public class Employee {
protected long employeeId;
protected String firstName;
protected String lastName;
public boolean equals(Object o){
if(o == null) return false;
if(!(o instanceof) Employee) return false;
Employee other = (Employee) o;
if(this.employeeId != other.employeeId) return false;
if(! this.firstName.equals(other.firstName)) return false;
if(! this.lastName.equals(other.lastName)) return false;
return true;
}
public int hashCode(){
return (int) employeeId;
}
}
// To get the index of selected item which triggered async task :
int itemIndex = EmployeeList.indexOf(selectedEmployeeModel);
recyclerView.scrollToPosition(itemIndex);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.