在RecyclerView中刷新数据并保持其滚动位置 [英] Refreshing data in RecyclerView and keeping its scroll position
问题描述
如何刷新RecyclerView
中显示的数据(在其适配器上调用notifyDataSetChanged
),并确保将滚动位置重设为原来的位置?
How does one refresh the data displayed in RecyclerView
(calling notifyDataSetChanged
on its adapter) and make sure that the scroll position is reset to exactly where it was?
如果ListView
良好,则只需检索getChildAt(0)
,检查其getTop()
,然后使用相同的准确数据调用setSelectionFromTop
.
In case of good ol' ListView
all it takes is retrieving getChildAt(0)
, checking its getTop()
and calling setSelectionFromTop
with the same exact data afterwards.
在RecyclerView
的情况下似乎不可能.
It doesn't seem to be possible in case of RecyclerView
.
我猜我应该使用确实提供scrollToPositionWithOffset(int position, int offset)
的LayoutManager
,但是检索位置和偏移量的正确方法是什么?
I guess I'm supposed to use its LayoutManager
which indeed provides scrollToPositionWithOffset(int position, int offset)
, but what's the proper way to retrieve the position and the offset?
layoutManager.findFirstVisibleItemPosition()
和layoutManager.getChildAt(0).getTop()
?
还是有一种更优雅的方式来完成工作?
Or is there a more elegant way to get the job done?
推荐答案
我使用了这个.^ _ ^
I use this one.^_^
// Save state
private Parcelable recyclerViewState;
recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();
// Restore state
recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);
这很简单,希望对您有帮助!
It is simpler, hope it will help you!
这篇关于在RecyclerView中刷新数据并保持其滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!