问题描述
我有一个带有几种物品类型的 RecyclerView
.看起来像这样:
I have a RecyclerView
with several items types. It looks like this:
- 2017年7月21日
- 消息1
- 消息2
- 消息3
- 2017年7月22日
- 消息4
- 新邮件标题
- 消息5
- 消息6
收到新邮件时,我按日期对其进行排序,然后调用 notifyDataSetChanged()
.它运作良好,但会自动在新物品的高度上滚动我的 RecyclerView
.在这种情况下,我不能使用 notifyItemInserted()
,因为我不知道排序后的项目位置.
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.
如何在不调用 notifyItemInserted()
的情况下强制 RecyclerView
在 notifyDataSetChanged()
之后滚动?
How to force RecyclerView
do not scroll after notifyDataSetChanged()
without call notifyItemInserted()
?
推荐答案
您可以尝试4种方法.因为我不知道您的视图的高度,所以我不确定它是否真的有效.但是,请尝试一下
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..您无法更改哪个特定项目.但是你知道这种变化的范围
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.在调用 notifyDataSetChanged()
yourList.clear();
mAdapter.notifyDataSetChanged();
III.在添加新项目之前/之后, ReyclerView
的保存/重置状态
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.使用此功能
mAdapter.notifyItemRangeChanged(0, list.size());
这篇关于notifyDataSetChanged之后如何防止RecyclerView中的自动滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!