Take a look at DiffUtil https://developer.android.com/reference/android/support/v7/util/DiffUtil.html
When you update your dataset in your adapter, you can use this tool to calculate the notifications needed to correctly present a new dataset.
Extend DiffUtil.Callback
and implement abstract methods (I create a constructor that looks like this:
public MyDiffCallback(ArrayList<String> oldList, ArrayList<String> newList) { this.oldList = oldList; this.newList = newList; }
I store oldList
and newList
in memory so that I can implement:
areItemsTheSame
areContentsTheSame
getNewListSize
getOldListSize
For instance:
@Override public int getOldListSize() { return oldList.size(); } @Override public int getNewListSize() { return newList.size(); } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { return oldList.get(oldItemPosition).equals(newList(newItemPosition)) } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { return areItemsTheSame(oldItemPosition, newItemPosition); }
areItemsTheSame
: indicates UTIL if the item is moved (marked position) areContentsTheSame
: Tells UTIL if the content of the item has changed.
Now you have the updateDataSet method (or whatever you called it!); do something like:
public updateDataSet(List newDataSet) { // this.dataSet is the old data set / List final MyDiffCallback callback = new MyDiffCallback(this.dataSet, newDataSet); final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(callback); this.dataSet = newDataSet; diffResult.dispatchUpdatesTo(this); //This is the Adapter }
Hope this helps, Woof
Link: https://medium.com/@iammert/using-diffutil-in-android-recyclerview-bdca8e4fbb00#.yhxirkkq6
source share