Diffutil in recycleview, making it autoscroll if a new item is added

If we use DiffUtil.Callback and do

 adapter.setItems(itemList); diff.dispatchUpdatesTo(adapter); 

how can we make sure that adding new items will scroll to this new position.

I have a case where I see an element that disappears, and a new one is created as the first element at the top, but not displayed. It is hidden from above until you scroll down to make it visible. Before using DiffUtil , I did it manually, and after I realized that I was inserting some kind of position (above), I could scroll.

+5
source share
2 answers

You have a dispatchUpdatesTo(ListUpdateCallback) method.

So you can just implement a ListUpdateCallback , which gives you the first element inserted

 class MyCallback implements ListUpdateCallback { int firstInsert = -1; Adapter adapter = null; void bind(Adapter adapter) { this.adapter = adapter; } public void onChanged(int position, int count, Object payload) { adapter.notifyItemRangeChanged(position, count, payload); } public void onInserted(int position, int count) { if (firstInsert == -1 || firstInsert > position) { firstInsert = position; } adapter.notifyItemRangeInserted(position, count); } public void onMoved(int fromPosition, int toPosition) { adapter.notifyItemMoved(fromPosition, toPosition); } public void onRemoved(int position, int count) { adapter.notifyItemRangeRemoved(position, count); } } 

and then just scroll through the RecyclerView manually

 myCallback.bind(adapter) adapter.setItems(itemList); diff.dispatchUpdatesTo(myCallback); recycler.smoothScrollToPosition(myCallback.firstInsert); 
+8
source

There is a simple way that also saves the user's scroll position if elements are pasted out of scope:

 import android.os.Parcelable; Parcelable recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState(); // apply diff result here (dispatch updates to the adapter) recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState); 

Using this approach, new elements become visible if they are inserted where the user can see them, but the user's point of view is preserved if the elements are inserted outside the view.

+11
source

Source: https://habr.com/ru/post/1266831/


All Articles