

LayoutManager.onSaveInstanceState() 不起作用,怎么回事?
source link: https://www.oschina.net/question/5376862_2323819
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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/2469247/LayoutManager-onSaveInstanceState()-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); }}
Recommend
-
92
VegaLayoutManager a customized LayoutManager - fade and shrink the head itemView when scrolling. ...
-
149
PagerLayoutManager 具有分页功能的 Recyclerview 布局管理器,主打分页,可以替代部分场景下的网格布局,线性布局,以及一些简单的ViewPager,但也有一定的局限性,请选择性使用。 1. 效果预览
-
89
Attention. This project is not maintained any more !!! vlayout 中文文档 Projects of Tangram Android Project
-
70
RecyclerView 里的自定义 LayoutManager 的一种设计与实现
-
73
README.md
-
24
README.md SaveState
-
37
如果你是一个有经验的 Android 程序员,那么你肯定手写过许多 onSaveInstanceState 以及 onRestoreInstanceState 方法用来保持 Activity 的状态,因为 Activity 在变为不可见以后,系统随时可能把它回
-
29
-
50
README.md
-
10
点 击 蓝 字 关 注 我 们 吧
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK