0

我正在尝试Icepick在我们的应用程序上使用库来保存和恢复手机轮换包,但是库文档我找不到保存的好技巧和通过@Parcel注释实现的类,这是我在页面上找到的简单类

Example班级:

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

    public Example(){ /*Required empty bean constructor*/ }

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

    public String getName() { return name; }
    public int getAge() { return age; }

    public String setName(String name) { this.name = name; }
    public int setAge(int age ) { this.age = age; }
}

ExampleBundler班级:

public class ExampleBundler implements Bundler<Object> {
    @Override
    public void put(String s, Object example, Bundle bundle) {
        bundle.putParcelable(s, Parcels.wrap(example));
    }

    @Override
    public Object get(String s, Bundle bundle) {
        return Parcels.unwrap(bundle.getParcelable(s));
    }
}

好的,现在我该如何使用它Activity

这是我尝试保存和恢复的简单代码

public class MainActivity extends BaseActivity {

  /* @State(ExampleBundler.class) String message; */

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Example example = new Example();
    example.setName = "HELLO WORLD";
    example.setAge = 99;
  }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    public void onRestoreInstanceState(Bundle inState) {
    }
}

你能修复我的代码吗?感谢提前

4

1 回答 1

3

要修复您的代码,捆绑器必须实现示例类而不是通用对象类,因此请更改

    public class ExampleBundler implements Bundler<Object> {
    @Override
    public void put(String s, Object example, Bundle bundle) {
        bundle.putParcelable(s, Parcels.wrap(example));
    }

    @Override
    public Object get(String s, Bundle bundle) {
        return Parcels.unwrap(bundle.getParcelable(s));
    }
}

对此

public class ExampleBundler implements Bundler<Example> {
    @Override
    public void put(String s, Example example, Bundle bundle) {
        bundle.putParcelable(s, Parcels.wrap(example));
    }

    @Override
    public Example get(String s, Bundle bundle) {
        return Parcels.unwrap(bundle.getParcelable(s));
    }
}

然后,您必须添加@State(ExampleBundler.class) Example example;到活动的顶部。在您的 onCreate 添加Icepick.restoreInstanceState(this, savedInstanceState)和您的 onSavedInstanceState 添加Icepick.saveInstanceState(this,outstate)

Icepick 文档打包器

于 2016-07-26T16:10:46.377 回答