简体   繁体   English

如何在notifyDataSetChanged之后阻止RecyclerView中的自动滚动?

[英]How to prevent auto scroll in RecyclerView after notifyDataSetChanged?

I have a RecyclerView with several items types. 我有一个包含多种项目类型的RecyclerView It looks like this: 它看起来像这样:

  • 07/21/2017 2017年7月21日
  • Message 1 消息1
  • Message 2 消息2
  • Message 3 消息3
  • 07/22/2017 2017年7月22日
  • Message 4 消息4
  • New messages header 新邮件标题
  • Message 5 消息5
  • Message 6 消息6

When new messages arrived I sort it by date and call notifyDataSetChanged() . 当新消息到达时,我按日期排序并调用notifyDataSetChanged() It works well, but it automatically scroll my RecyclerView on new item(s) height. 它运行良好,但它会自动在新项目高度上滚动我的RecyclerView In this case I cannot use notifyItemInserted() because I don't know item position after sorting. 在这种情况下,我不能使用notifyItemInserted()因为我不知道排序后的项目位置。

How to force RecyclerView do not scroll after notifyDataSetChanged() without call notifyItemInserted() ? 如何强制RecyclerView不要在notifyDataSetChanged()之后滚动而不调用notifyItemInserted()

There are 4 ways you can try. 有4种方法可以尝试。 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. I.您没有可以更改哪个特定项目。 But you know the range of that change 但是你知道这种变化的范围

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

II. II。 Clear list before call notifyDataSetChanged() 调用notifyDataSetChanged()之前清除列表

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

III. III。 Save/Reset state of ReyclerView before/after adding new item 在添加新项目之前/之后保存/重置ReyclerView状态

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

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

IV. IV。 Use this function 使用此功能

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

Have you played with myRecView.getLayoutManager().setStackFromEnd(boolean) ? 你玩过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. 如果您可以确定在对可见部分上方或下方进行排序之后是否已插入新项目,并且在此调用setStackFromEnd ()函数中使用true或false,则可以避免滚动。

I do not know if it will really work .... 我不知道它是否真的有效......

You can know where the new item has been inserted using list.indexOf(yourItem) on your list of items. 您可以使用列表中的list.indexOf(yourItem)知道新项目的插入list.indexOf(yourItem) Then you can call notifyItemInserted() 然后你可以调用notifyItemInserted()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM