我有一个使用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);