【问题标题】:Saving Android Activity or Fragment state using Parceler使用 Parceler 保存 Android Activity 或 Fragment 状态
【发布时间】:2016-12-16 21:39:59
【问题描述】:

我正在使用 parceler 库。我用 this 制作了一个复杂的对象。正如它所说,它使对象可打包,所以我想用它来保存片段状态。

这是我的模型

@Parcel
public class Example {
    String name;
    int age;

    public Example() {}

    public Example(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() { return name; }

    public int getAge() { return age; }
}

在我的片段中我有这个

   ArrayList<Example> exampletLists;

但是当我尝试将其放入 onSaveInstanceState

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelableArrayList("EXAMPLE_LIST",exampletLists); //this is what I want to do , but I can't 
}

我想在 onCreate Like 中获取值

 if (savedInstanceState != null) {
    exampletLists = savedInstanceState.getParcelableArrayList(EXAMPLE_LIST);
 }

我怎样才能用这个库实现这一点?

【问题讨论】:

  • @shurvo 你能简单解释一下你的问题吗?
  • 我有一个回收站视图,它通过网络服务显示一些项目。每次我旋转屏幕时,都会再次调用 Web 服务。为了避免这种情况,我必须保存状态。我要设置的变量是 List of Example 。所以我必须让 Example 类 Parcelable ,所以我可以把它放到 outState.putParcelableArrayList ,我已经使用这个库做了类 Example Parcelable ,我不能把它放在 outState.putParcelableArrayList
  • 您在 putParcelable 中遇到什么错误?
  • 这是说 exampletLists 必须是 Parcelable 范围

标签: android android-fragments android-activity android-savedstate parceler


【解决方案1】:

Parceler 可以包装 ArrayLists,因此您可以在编写和读取 `savedInstanceState 时使用 Parcels.wrap()Parcels.unwrap() 方法:

public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelable("EXAMPLE_LIST", Parcels.wrap(exampletLists));
}

public void onCreate(Bundle savedInstanceState) {
    //...
    if (savedInstanceState != null) {
        exampletLists = Parcels.unwrap(savedInstanceState.getParcelable(EXAMPLE_LIST));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多