Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

RecyclerView local refresh

RecyclerView began from Android 5.0 system, it has been several years to now, we slowly also from ListView to RecyclerView, the use of RecyclerView will feel or RecyclerView incense, with universal adapter used together, A list can be implemented in very compact code, and the extended spiritual activity is much higher. This article mainly describes the local refresh of RecyclerView.

Why do I need a local refresh

It is convenient to refresh all data by simply calling notifyDataSetChanged(), but there is a performance penalty to refresh all data in a loop. When there is a lot of data, a partial refresh can save performance.

How to implement local refresh

Add data

Add data at an index

public final void notifyItemInserted(int position)
Copy the code

Batch add (starting index position, number of changes)

public final void notifyItemRangeInserted(int positionStart, int itemCount)
Copy the code

Delete the data

Removes data at an index

public final void notifyItemRemoved(int position)
Copy the code

Batch delete (start index position, number of changes)

public final void notifyItemRangeRemoved(int positionStart, int itemCount)
Copy the code

Update the data

Update data at an index

public final void notifyItemChanged(int position) 
Copy the code

Batch update (starting index position, number of changes)

public final void notifyItemRangeChanged(int positionStart, int itemCount)
Copy the code

Update some components of Item

Updating Item data is simple, but can you update only individual components of an Item?

Because when you update a complete Item, the image in the Item will be reloaded and will flicker.

Can you update just a single component? The answer is yes.

This requires us to use notifyItemChanged(int Position, @nullable Object Payload) and do the logic in the ViewHolder, because the program needs you to specify the logic for local updates in the Item.

NotifyItemChanged (getAdapterPosition()," Item component local update ");Copy the code
@Override public void onBindViewHolder(ViewHolder holder, int position, List<Object> payloads) { if (payloads.isEmpty()) { onBindViewHolder(holder, position); } else { ItemBean itemBean=data.get(position); Holder.tv1. SetText (ItemBean.str1 + payload.get (0))); holder.tv2.setText(itemBean.str2 + payloads.get(1)); }}Copy the code