1

我正在使用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);
 }

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

4

1 回答 1

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));
    }
}
于 2016-08-11T16:37:34.780 回答