How to prevent auto scroll in RecyclerView after notifyDataSetChanged?

☆樱花仙子☆ 提交于 2019-12-22 12:37:32

问题


I have a RecyclerView with several items types. It looks like this:

  • 07/21/2017
  • Message 1
  • Message 2
  • Message 3
  • 07/22/2017
  • Message 4
  • New messages header
  • Message 5
  • Message 6

When new messages arrived I sort it by date and call notifyDataSetChanged(). It works well, but it automatically scroll my RecyclerView on new item(s) height. In this case I cannot use notifyItemInserted() because I don't know item position after sorting.

How to force RecyclerView do not scroll after notifyDataSetChanged() without call notifyItemInserted()?


回答1:


There are 4 ways you can try. Because I don't know what is the height of your view, so I can't sure if it really works. But let give it a try

I. You don't which specific item could be changed. But you know the range of that change

mAdapter.notifyItemInserted(position);                 
mAdapter.notifyItemRangeChanged(0, list.size());

II. Clear list before call notifyDataSetChanged()

yourList.clear();
mAdapter.notifyDataSetChanged();

III. Save/Reset state of ReyclerView before/after adding new item

    // Save state
    private Parcelable recyclerViewState;
    recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();

    // Restore state
    recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);

IV. Use this function

mAdapter.notifyItemRangeChanged(0, list.size());



回答2:


Have you played with myRecView.getLayoutManager().setStackFromEnd(boolean) ?

If you can determine if the new item has been inserted after sorting above or below the visible part and in function of this call setStackFromEnd () with true or false maybe you can avoid the scroll.

I do not know if it will really work ....




回答3:


You can know where the new item has been inserted using list.indexOf(yourItem) on your list of items. Then you can call notifyItemInserted()



来源:https://stackoverflow.com/questions/45325621/how-to-prevent-auto-scroll-in-recyclerview-after-notifydatasetchanged

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!