I'd like to update a single item in my RecyclerView. The item is just POJO bean that holds isFavourite
flag. User can click on item and set/unset as favourite. I have implemented adater with DiffUtil callback. There is one callback method boolean areContentsTheSame (int oldItemPosition, int newItemPosition)
but in my case old and new item is the same object so there is nothing to compare ( equals method returns true). Should I save previous flag value and then check for changes or is any simple solution?
This is my solution. I don't use DiffUtil instead of I use notifyItemChanged(int position, Object payload). payload variable contains data that you want to update. Please refer below code:
public void updateMedication(MedicationRecord medication) {
int index = mData.indexOf(medication);
notifyItemChanged(index);
Bundle diffPayLoad = new Bundle();
diffPayLoad.putInt("notify", medication.getNotify());
notifyItemChanged(index, diffPayLoad);
}
In RecyclerView.Adapter, add this function to handle the payload
@Override
public void onBindViewHolder(@NonNull SharedMedVH holder,
int position,
@NonNull List<Object> payloads) {
if (payloads.isEmpty()) {
super.onBindViewHolder(holder, position, payloads);
} else {
Bundle o = (Bundle) payloads.get(0);
for (String key : o.keySet()) {
if (key.equals("notify")) {
holder.updateNotify(o.getInt("notify"));
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With