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

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

问题描述

我正在将我的 ListViews 迁移到 RecyclerViews.对于列表视图,我使用了描述的常用技术 在这里存储和恢复活动之间的滚动位置.

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() 好像有protected 访问权限,所以不能直接使用.

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

推荐答案

好的,来回答我自己的问题.据我了解,由于他们已经将布局代码和视图回收代码(因此得名)解耦,因此负责保持布局状态(并恢复它)的组件现在是 LayoutManager 中使用的您的回收商视图.

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
    if(state != null)
        mListState = state.getParcelable(LIST_STATE_KEY);
}

然后更新LayoutManager(我在onResume()中做了):

Then update the LayoutManager (I do in onResume()):

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

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

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

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