中的数据并保持其滚动位置

中的数据并保持其滚动位置

本文介绍了刷新 RecyclerView 中的数据并保持其滚动位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何刷新 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?

如果好的 ol' 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.

我想我应该使用它的 LayoutManager,它确实提供了 scrollToPositionWithOffset(int position, int offset),但是检索位置和抵消?

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?

推荐答案

我用这个.^_^

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

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

比较简单,希望对你有帮助!

It is simpler, hope it will help you!

这篇关于刷新 RecyclerView 中的数据并保持其滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 15:55