![](/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.