Junior — Middle
What methods can be used to implement partial updates of items in a RecyclerView list?
sobes.tech AI
Answer from AI
To partially update items in a RecyclerView list, you can use the following methods:
-
notifyItemChanged(position, payload) — notifies the adapter that the item at
positionhas changed, andpayloadallows passing information about what exactly has changed. This helps optimize the update and redraw only the necessary parts of the View. -
DiffUtil — a utility for calculating the difference between the old and new list. It allows updating only the changed items by calling the appropriate adapter notification methods.
-
Using ViewHolder with methods that update only the changed fields based on
payload.
Example of using notifyItemChanged with payload:
// In the adapter
override fun onBindViewHolder(holder: ViewHolder, position: Int, payloads: MutableList<Any>) {
if (payloads.isEmpty()) {
super.onBindViewHolder(holder, position, payloads)
} else {
val payload = payloads[0] as Bundle
// Update only the necessary fields, for example:
if (payload.containsKey("KEY_NAME")) {
holder.nameTextView.text = payload.getString("KEY_NAME")
}
}
}
// When updating an item
val payload = Bundle().apply { putString("KEY_NAME", "New Name") }
adapter.notifyItemChanged(position, payload)
This approach helps avoid full redraw of the item and improves performance.