【问题标题】:Saving RecyclerView list State保存 RecyclerView 列表状态
【发布时间】:2017-06-16 06:06:50
【问题描述】:

我有一个包含类对象列表的 recyclerView。目前,当我关闭我的应用程序时,recyclerView 中的所有列表都会丢失,并且在重新启动应用程序后,recyclerView 什么都不显示(没有列表)。

即使在我的关闭和销毁之后,我应该使用什么以及如何保留列表?

public class Info  {
public String pName;
public String pContact;
public Character pGender;
public int pID;
public String tDateTime;   // today's date and time
}

我将此类的对象存储在 arraylist 中以填充我的 recyclerview 适配器。

【问题讨论】:

  • 你可以使用本地数据库来存储这个链接androidauthority.com/…的数据
  • 您的列表中显示了哪些数据?你能分享你的来源吗?
  • 如何填写数据?无论如何,我需要那个来源。如果您手动填写数据,通过 EditText 输入,那么您应该使用 sqlite 数据库。
  • 上面添加的类信息显示在列表中。
  • 是的,我通过 Edittext 填充数据

标签: android android-recyclerview onsaveinstancestate onrestoreinstancestate


【解决方案1】:

保存状态:

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

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

恢复状态:

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:

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

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

【讨论】:

  • 我试过了,但没用。关闭应用后,RecyclerView 仍然为空。
【解决方案2】:

覆盖 Activity 中的 onSaveInstanceState 并保存模型的状态,而不是布局管理器的状态。如果视图显示任何数据,您肯定在某处拥有数据模型。

至少,您只需要记住模型中当前的项目数。这是如果模型能够从某个地方获取所需项目的内容。如果不是,或者花费的时间太长,则状态还需要包括正在显示的项目。类似的东西

@Override
public void onSaveInstanceState(Bundle outState) {
  super.onSaveInstanceState(outState);
  outState.putSerializable("d.list.data", adapter.getState());
}

并且,必须恢复状态:

if (savedInstanceState != null) {
  adapter.setState(savedInstanceState.getSerializable("d.list.data"));
}

Here 是为 RecyclerView 使用的模型保存和应用状态的类的代码。

【讨论】:

  • 链接中断 :(
  • 链接现在应该已修复。感谢您的报告。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多