Partial update of RecyclerView.ViewHolder

12,292

You can notify your RecyclerView.Adapter's observers to issue a partial update of your RecyclerView.ViewHolders by passing a payload Object.

notifyItemRangeChanged(positionStart, itemCount, payload);

Where payload could be or contain a flag that represents relative or absolute time. To bind the payload to your view holders, override the following onBindViewHolder(viewHolder, position, payloads) method in your adapter, and check the payloads parameter for data.

@Override
public void onBindViewHolder(MyViewHolder viewHolder, int position, List<Object> payloads) {
    if (payloads.isEmpty()) {
        // Perform a full update
        onBindViewHolder(viewHolder, position);
    } else {
        // Perform a partial update
        for (Object payload : payloads) {
            if (payload instanceof TimeFormatPayload) {
                viewHolder.bindTimePayload((TimeFormatPayload) payload);
            }
        }
    }
}

Within your MyViewHolder.bindTimePayload(payload) method, update your time TextViews to the time format specified in the payload.

Share:
12,292
Remc4
Author by

Remc4

Java, Android and MariaDB.

Updated on June 18, 2022

Comments

  • Remc4
    Remc4 almost 2 years

    I'm trying to change the field with time in my RecyclerView. Each individual ViewHolder contains a CardView and a few more views inside. The only view I want to animate is the one with time. As you can see, there is no animation:

    adapter.notifyDataSetChanged();
    

    RecyclerView with no animations

    Updating items one by one doesn't help because then the whole CardView flashes:

    int len = adapter.getItemCount();
    for(int i=0;i<len;i++) {
        adapter.notifyItemChanged(i);
    }
    

    enter image description here

    Is there a way to get a list of all ViewHolders to then update (animate) just that one TextView inside each one?

  • Remc4
    Remc4 almost 8 years
    Works beautifully. Thank you very much.
  • Bawender Yandra
    Bawender Yandra about 6 years
    Brother you saved the day, worked like a charm, I was about to change the recycler view to viewpager. But you answer also made me learn as well as saved my lots of hours of hardwork
  • Tyler Turnbull
    Tyler Turnbull about 4 years
    Thank you Ryan . Thank you, Thank you, Thank you!
  • DragonFire
    DragonFire about 3 years
    see here : stackoverflow.com/a/38796098/3904109 for a good explanation and working example.