Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView scroll to top with AsyncListDiffer not working

I am using RecyclerView with AsyncListDiffer (calculates and animates differences between old and new items, all on background thread).

I have a button to sort the list. After I sort it and re-set it to RecyclerView using mDiffer.submitList(items); I also call recyclerView.scrollToPosition(0) or (smoothScrollToPosition(0)), but it has no effect.

I think this behaviour is expected, as AsyncListDiffer is probably still calculating differences at the time that scrollToPosition(0) is called, so it has no effect. Additionally, by default AsyncListDiffer does not scroll back to top, but instead it keeps RecyclerView in the same state.

But how do I tell the RecyclerView to scroll to top after AsyncListDiffer is done and updates it?

like image 370
c0dehunter Avatar asked Mar 20 '19 13:03

c0dehunter


2 Answers

This got answered here:

https://stackoverflow.com/a/55264063/1181261

Basically, if you submit the same list with different order, it will be ignored. So first you need to submit(null) and then submit your re-ordered list.

like image 200
c0dehunter Avatar answered Sep 19 '22 23:09

c0dehunter


I am concerned that while .submitList(null) may have worked for you, it only refreshed your entire RecyclerView without rendering the desired animated list updates.

Solution is to implement the .submitList( List<T> list) method inside your ListAdapter as follows:

public void submitList(@Nullable List<T> list) {
    mDiffer.submitList(list != null ? new ArrayList<>(list) : null);
}

This way you allow the ListAdapter to retain its currentList and have it "diffed" with the newList, thereby the animated updates, as opposed to "diffing" with a null.

like image 31
aLL Avatar answered Sep 17 '22 23:09

aLL