LayoutManager.onSaveInstanceState() 不起作用,怎么回事?

我想GridLayoutManager 保存我的RecyclerView的状态,但是当调用 onSaveInstanceState() 的时总是返回同一个对象.我用方法"findFirstVisibleItemPosition"时,它总是返回 -1.

RecyclerView 有适配器,适配器有一些元素,我可以滚动它们!我不知道为什么无法获得完全初始化和工作组件的项目位置!请帮忙!

这是我的代码:

@Override
protected void onSaveInstanceState(Bundle outState) {

super.onSaveInstanceState(outState);

outState.putParcelable(BUNDLE_MOVIES_RECYCLER_VIEW_STATE, mMoviesRecyclerView.getLayoutManager().onSaveInstanceState());

outState.putInt(BUNDLE_SEGMENT_POSITION, mSelectedFilterPosition);
outState.putSerializable(BUNDLE_NOW_PLAYING_MOVIE, mNowPlayingMovie);
outState.putSerializable(BUNDLE_SEGMENTED_MOVIES, mSegmentMovies);

}
解决方案参考了这个帖子:https://www.itbaoku.cn/post/2...()-not-working
解决方案
问题已解决!为了保存布局管理器的状态,需要在活动的 onPause 方法中调用 LayoutManager.onSaveInstanceState() 方法.因为在活动 LayoutManager 的 onSaveInstanceState 中已经将其从视图中清除,或者只是删除布局配置.代码示例:
public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; private Parcelable mLayoutManagerState; private static final String LAYOUT_MANAGER_STATE = "LAYOUT_MANAGER_STATE"; @Override protected void onPause() { super.onPause(); mLayoutManagerState = recyclerView.getLayoutManager().onSaveInstanceState(); } @Override public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) { super.onCreate(savedInstanceState, persistentState); recyclerView = (RecyclerView) findViewById(R.id.recyclerview); if (savedInstanceState != null) { mLayoutManagerState = savedInstanceState.getParcelable(LAYOUT_MANAGER_STATE); recyclerView.getLayoutManager().onRestoreInstanceState(mLayoutManagerState); } } @Override public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) { super.onSaveInstanceState(outState, outPersistentState); outState.putParcelable(LAYOUT_MANAGER_STATE, mLayoutManagerState); }}

你可能感兴趣的