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

后端 未结 3 1065
栀梦
栀梦 2021-01-01 14:00

If we use DiffUtil.Callback, and do

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

how can we make sure that ad

3条回答
  •  被撕碎了的回忆
    2021-01-01 14:19

    There's an easy way to do this that also preserves the user's scroll position if items are inserted outside the viewable area:

    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, the new items are made visible if they are inserted where the user can see them -- but the user's viewpoint is preserved if the items are inserted outside of view.

提交回复
热议问题