how to update the data in specific position in the recyclerview without notifying the whole item? (Ex. text, image etc)

116 Views Asked by At

I need the functionality to update the data in the item in the recycler view. right now, If we notify the whole item it shows some fluctuation and we want to avoid refreshing the whole item on the UI.

I am using the ListAdapter with diff utils.

3

There are 3 best solutions below

7
Agent_L On BEST ANSWER

There are many ways to achieve your goal.

  1. self-managing items. Adapter doesn't know anything about content of the items, it only puts items into RecyclerView. Content is managed by the item itself, so your problem is already solved.
  2. custom adapter. Adapter has intricate knowledge about every item and can update selected ones accordingly.
  3. AsyncListDiffer You can add differ to your adapter and it will take care of not updating parts that need no update.

Without seeing your code, we can't tell which way would be the most appropriate for you, but I guess adding differ is the simplest on already working code.

0
Francesco Bocci On
0
cactustictacs On

If you're talking about updating specific list items, and you're not using a DiffUtil (which will handle it for you) then you need to call the appropriate notify* method on your Adapter.

They fall into two categories, item change events (where the item list stays the same, but the displayed data for one or more of those items changes) and structural change events (where the actual list of items changes in some way, e.g. insertion/removal, or reordering).

I'm assuming you just want to update the displayed data for an item, so you should use one of the notifyItemChanged or notifyItemRangeChanged methods to inform the adapter that a certain item (or range of items) needs to update. If any of those items are currently being displayed in a ViewHolder, then onBindViewHolder will get called again for those items - which is where you set all your text, images etc depending on the item you're displaying. So you'll update them with the current data.

Both those methods have a version that takes a payload Object/Any, where you can pass in some data to be used in a partial bind - basically, onBindViewHolder can receive that data and be smarter about the update, which means you can avoid things like reloading images, etc. by passing in some stuff and checking for it during the binding process. More info about that here in the other version of onBindViewHolder you can implement, if you need to.