存储和还原RecyclerView位置不起作用 [英] Store and restore RecyclerView position not working
问题描述
我正在使用GridLayoutManager作为片段内的RecyclerView的LayoutManager,并且RecyclerView适配器由加载程序填充. 我尝试在设备旋转时存储和还原GridLayoutManager的状态,但无法正常工作,但仍返回到初始状态"RecyclerView中的第一个元素".
I am using GridLayoutManager as LayoutManager for RecyclerView inside a fragment , and RecyclerView adapter get populated by loader. I tried to store and restore state of GridLayoutManager on device rotation but not working and still get back to the initial state "first element in RecyclerView".
onSaveInstanceState方法:
onSaveInstanceState method:
@Override
public void onSaveInstanceState(Bundle outState) {
mRecylcerViewParecelable = mGridView.getLayoutManager().onSaveInstanceState();
outState.putParcelable(GRID_LAYOUT_PARCEL_KEY, mRecylcerViewParecelable);
super.onSaveInstanceState(outState);
}
onViewStateRestored方法:
onViewStateRestored method:
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
if(savedInstanceState!=null){
mRecylcerViewParecelable = savedInstanceState.getParcelable(GRID_LAYOUT_PARCEL_KEY);
}
super.onViewStateRestored(savedInstanceState);
}
onLoadFinished方法:
onLoadFinished method:
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mMovieAdapter.swapCursor(data);
mGridView.getLayoutManager().onRestoreInstanceState(mRecylcerViewParecelable);}
推荐答案
尝试在处理程序中包装onRestoreInstanceState()
:
Try to wrap onRestoreInstanceState()
inside Handler:
new Handler().postDelayed(new Runnable() {
@Override public void run() {
mGridView.getLayoutManager().onRestoreInstanceState(listState);
}
}, 300);
延迟onRestoreInstanceState
是一个黑客.
我遇到了同样的问题,IMO,看起来RecyclerView一直回到初始状态,因为当我们调用onRestoreInstanceState
时,仍会填充Adapter中的数据.
It's a hack to delay the onRestoreInstanceState
.
I've experienced the same issue, IMO it looks like the RecyclerView keeps going back to initial state because the data in Adapter still being populated when we call the onRestoreInstanceState
.
这篇关于存储和还原RecyclerView位置不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!