RecyclerView存储/恢复活动之间的状态 [英] RecyclerView store / restore state between activities

查看:915
本文介绍了RecyclerView存储/恢复活动之间的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我迁移我的列表视图来RecyclerViews。随着列表视图我用描述的公共技术<一href="http://stackoverflow.com/questions/3014089/maintain-save-restore-scroll-position-when-returning-to-a-listview/5688490#5688490">here保存和恢复活动之间的滚动位置。

I'm migrating my ListViews to RecyclerViews. With listviews I used the common technique described here to store and restore scroll position between activities.

如何使用RecyclerViews做?在 RecyclerView.onSaveInstanceState()似乎有保护的访问,所以不能直接使用。

How to do the same with RecyclerViews? the RecyclerView.onSaveInstanceState() seem to have protected access, so can't be used directly.

推荐答案

好了,回答我的问题。据我了解,因为他们已经分离了布局code和看法回收code(因而名字),该组件负责一个用于保持的布局状态(和恢复它)现在是布局管理在recyclerview使用。

Ok, so to answer my own question. As I understand it, since they've decoupled the layout code and the view recycling code (thus the name), the component responsible one for holding layout state (and restoring it) is now the LayoutManager used in your recyclerview.

因此​​,你用同样的模式,而是存储状态的布局管理器并没有recyclerview:

Thus, to store state you use same pattern, but on the layout manager and not the recyclerview:

protected void onSaveInstanceState(Bundle state) {
     super.onSaveInstanceState(state);

     // Save list state
     mListState = mLayoutManager.onSaveInstanceState();
     state.putParcelable(LIST_STATE_KEY, mListState);
}

在恢复状态的 onRestoreInstanceState()

protected void onRestoreInstanceState(Bundle state) {
    super.onRestoreInstanceState(state);

    // Retrieve list state and list/item positions
    mListState = state.getParcelable("myState");
}

然后更新布局管理(我在 onResume()):

@Override
protected void onResume() {
    super.onResume();

    if (mListState != null) {
        mLayoutManager.onRestoreInstanceState(mListState);
    }
}

这篇关于RecyclerView存储/恢复活动之间的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆