我正在尝试在我们的应用程序上使用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) {
}
}
你可以修复我的代码吗?谢谢提前
答案 0 :(得分:3)
要修复代码,bundle必须实现示例类而不是通用对象类,所以更改
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)