我在片段中使用 GridLayoutManager 作为 RecyclerView 的 LayoutManager,并且 RecyclerView 适配器由加载器填充。我尝试在设备旋转时存储和恢复 GridLayoutManager 的状态,但无法正常工作,并且仍然回到初始状态“RecyclerView 中的第一个元素”。
onSaveInstanceState 方法:
@Override
public void onSaveInstanceState(Bundle outState) {
mRecylcerViewParecelable = mGridView.getLayoutManager().onSaveInstanceState();
outState.putParcelable(GRID_LAYOUT_PARCEL_KEY, mRecylcerViewParecelable);
super.onSaveInstanceState(outState);
}
onViewStateRestored 方法:
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
if(savedInstanceState!=null){
mRecylcerViewParecelable = savedInstanceState.getParcelable(GRID_LAYOUT_PARCEL_KEY);
}
super.onViewStateRestored(savedInstanceState);
}
onLoadFinished 方法:
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mMovieAdapter.swapCursor(data);
mGridView.getLayoutManager().onRestoreInstanceState(mRecylcerViewParecelable);}