Android uses DiffUtil deal with the problem RecyclerView update data

background

  1. RecyclerView.Adapter#notifyDataSetChanged() Every time will refresh the entire layout;
  2. Each time manually invoke RecyclerView.Adapter#notifyItemXxseries method is cumbersome;
  3. Repeat if necessary with the old list item in the new project, only updated content, rather than inserting duplicates.

DiffUtil

DiffUtilIt is to simplify the operation to update data RecyclerVeiw born. The key classes and methods are as follows:

class method description
DiffUtil public static DiffResult calculateDiff(Callback cb) The analysis of the data provided by the difference Callback old and new data list, return DiffResult
DiffUtil.Callback public abstract int getOldListSize() Returns the number of old data
public abstract int getNewListSize() Returns the number of new data
public abstract boolean areItemsTheSame(int oldItemPosition, int newItemPosition) Decide whether two data items are the same
public abstract boolean areContentsTheSame(int oldItemPosition, int newItemPosition) (When the two data items are the same, the) decides whether the contents of two data items of the same, or need to be updated
DiffUtil.DiffResult public void dispatchUpdatesTo(final RecyclerView.Adapter adapter) The difference in updates to RecyclerView.Adapter

step

  1. Creating a class that implements DiffUtil.Callback;
  2. When the arrival of new data, callback instantiates custom, old and new incoming transactions;
  3. In the thread of the call DiffUtil#calculateDiffcalculate the difference;
  4. The differences in the results DiffResultupdated to RecyclerView.Adapter in.

More

  • Use android.support.v7.recyclerview.extensions.ListAdapterandandroid.support.v7.recyclerview.extensions.AsyncListDiffer

Guess you like

Origin www.cnblogs.com/lshare/p/11333993.html