我正在将我的 ListViews 迁移到 RecyclerViews。对于 ListView ,我使用了 here 所描述的常用技术。存储和恢复 Activity 之间的滚动位置。
如何对 RecyclerViews 做同样的事情? RecyclerView.onSaveInstanceState()
似乎有 protected
访问权限,所以不能直接使用。
最佳答案
好的,所以回答我自己的问题。据我了解,由于他们已经将布局代码和 View 回收代码(因此得名)解耦,因此负责保持布局状态(并恢复它)的组件现在是 LayoutManager
你的回收站 View 。
因此,要存储状态,您使用相同的模式,但在 布局管理器 上而不是 recyclerview:
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
// Save list state
mListState = mLayoutManager.onSaveInstanceState();
state.putParcelable(LIST_STATE_KEY, mListState);
}
在onRestoreInstanceState()
中恢复状态:
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
// Retrieve list state and list/item positions
if(state != null)
mListState = state.getParcelable(LIST_STATE_KEY);
}
然后更新LayoutManager(我在onResume()
中做):
@Override
protected void onResume() {
super.onResume();
if (mListState != null) {
mLayoutManager.onRestoreInstanceState(mListState);
}
}
关于android - RecyclerView 存储/恢复 Activity 之间的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28236390/