最后我找到了如何只更新 RecyclerView 中一行的特定视图。
(1) 在适配器中重写 onBindViewHolder(Recycler.ViewHolder VH, int position, List payloads)
(2) 在 onBindViewHolder 方法内部,
if(payloads != null && !payloads.isEmpty() && (payloads.get(0) instanceof customObject)){
// update the specific view
}else{
// I have already overridden the other onBindViewHolder(ViewHolder, int)
// The method with 3 arguments is being called before the method with 2 args.
// so calling super will call that method with 2 arguments.
super.onBindViewHolder(holder,position,payloads);
}
(3) 所以要通知数据变化和更新视图,需要调用notifyItemChanged(int position, Object payload)。需要将customObject(保存数据的模型)作为payload对象传递。
adapter.notifyItemChanged(i, obj);
注意:需要禁用 RecyclerView 的 ItemAnimator(默认启用)。否则有效载荷对象将为空。
recyclerView.setItemAnimator(null);
或
((SimpleItemAnimator)recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
更新:我最近使用了这个方法,没有禁用 ItemAnimator。所以不需要禁用 ItemAnimator。 - (recyclerview-v7:25.4.0)
for further reference