查看: 1684|回复: 0

[笔记] LayoutManager.onSaveInstanceState() 不起作用,怎么回事?

[复制链接]
论坛徽章:
0
跳转到指定楼层
1#
发表于 2021-9-9 14:06 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
我想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); }}

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

TOP技术积分榜 社区积分榜 徽章 团队 统计 知识索引树 积分竞拍 文本模式 帮助
  ITPUB首页 | ITPUB论坛 | 数据库技术 | 企业信息化 | 开发技术 | 微软技术 | 软件工程与项目管理 | IBM技术园地 | 行业纵向讨论 | IT招聘 | IT文档
  ChinaUnix | ChinaUnix博客 | ChinaUnix论坛
CopyRight 1999-2011 itpub.net All Right Reserved. 北京盛拓优讯信息技术有限公司版权所有 联系我们 未成年人举报专区 
京ICP备16024965号-8  北京市公安局海淀分局网监中心备案编号:11010802021510 广播电视节目制作经营许可证:编号(京)字第1149号
  
快速回复 返回顶部 返回列表