我想保存和恢复一些数据以用于屏幕方向更改(人像/风景)。
为此,我在保存要还原列表的类中实现了onSaveInstanceState和onRestoreInstanceState。似乎可行,在MyObject类中,我实现了 Parcelable 。
问题是我的对象扩展了GifImageButton 并实现了可打包的,所以我在对象构造函数中遇到此错误:“pl.droidsonroids.gif.GifImageButton没有默认的构造函数”
public class MyDerivedClass extends MyBaseClass { // extends AppCompatActivity
ArrayList<MyObject> list;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.episode_five);
if(savedInstanceState == null || !savedInstanceState.containsKey("key")) {
String[] colors = {"black", "red"};
String[] numbers = {"one", "two"};
list = new ArrayList<MyObject>();
for(int i = 0; i < numbers.length; i++)
list.add(new MyObject(numbers[i], colors[i]));
}
else {
list = savedInstanceState.getParcelableArrayList("key");
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList("key", list);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle inState) {
list = inState.getParcelableArrayList("key");
super.onSaveInstanceState(inState);
init();
}
public void init() {
list.add(new MyObject("three", "transparent"));
list.add(new MyObject("for", "white"));
}
}
,对于问题,请查看下面的代码:
我想扩展GifImageButton ,但随后出现错误“在pl.droidsonroids.gif.GifImageButton没有可用的默认构造函数”:
公共MyObject(字符串编号,字符串颜色)
AND 公共MyObject(放入)
注意:如果删除:“扩展GifImageButton”和“公共MyObject(Context context,AttributeSet attrs)”,则会编译代码。
class MyObject extends GifImageButton implements Parcelable {
String color;
String number;
public MyObject(Context context, AttributeSet attrs) {
super(context, attrs);
setImageResource(R.drawable.a);
}
public MyObject(String number, String color) {
this.color = color;
this.number = number;
}
private MyObject(Parcel in) {
color = in.readString();
number = in.readString();
}
public int describeContents() {
return 0;
}
@Override
public String toString() {
return number + ": " + color;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(color);
out.writeString(number);
}
public static final Parcelable.Creator<MyObject> CREATOR = new Parcelable.Creator<MyObject>() {
public MyObject createFromParcel(Parcel in) {
return new MyObject(in);
}
public MyObject[] newArray(int size) {
return new MyObject[size];
}
};
}
我可以在实现Parcelable的对象类中扩展GifImageButton吗?如果没有,我该如何解决?
最佳答案
出现错误消息是因为您需要在构造函数中调用超类的构造函数。如果没有显式调用,则编译器将插入不带参数的构造函数的调用。但是,所有超类构造函数都有一些自变量,这就是编译失败的原因。
就您而言,我根本不会在您的 class 中实现Parcelable
。超类没有实现它,因此您还需要以某种方式保存超类的状态,这是不可能的。超类是View
,因此它保留了对当前 Activity 的引用,该引用不能放入Parcel
中。
相反,您要做的不是保存实例本身,而是保存所需的状态。您的状态当前由两个字符串表示。您可以在State
内创建一个单独的类MyObject
:
static class State implements Parcelable {
private String color;
private String number;
//Parcelable implementation omitted
}
然后,您为其实现
Parcelable
。 MyObject
将具有一个字段private State state
而不是当前的两个字段,一个构造函数采用State
,而方法State getState()
则将返回状态。当需要保存状态时,无需保存对象,而是获取其状态并保存。当需要还原时,首先还原State
,然后将其与构造函数一起使用,以创建具有与以前相同状态的新MyObject
。