我有一个可打包类 A
和 B
延伸 A
例子:
A类
public abstract class A implements Parcelable {
private int a;
protected A(int a) {
this.a = a;
}
public int describeContents() {
return 0;
}
public static Creator<A> getCreator() {
return CREATOR;
}
public static final Parcelable.Creator<A> CREATOR = new Parcelable.Creator<A>() {
public A createFromParcel(Parcel in) {
return new A(in);
}
public A[] newArray(int size) {
return new A[size];
}
};
public void writeToParcel(Parcel out, int flags) {
out.writeInt(a);
}
protected A(Parcel in) {
a = in.readInt();
}
}
B类继承人
public class B extends A {
private int b;
public B(int a, int b) {
super(a);
this.b = b;
}
public static Creator<B> getCreator() {
return CREATOR;
}
public static final Parcelable.Creator<B> CREATOR = new Parcelable.Creator<B>() {
public B createFromParcel(Parcel in) {
return new B(in);
}
public B[] newArray(int size) {
return new B[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(b);
}
private B(Parcel in) {
super(in);
b = in.readInt();
}
}
在 B 中,我得到错误 “返回类型与 A.getCreator() 不兼容” 在
public static Creator<B> getCreator() {
return CREATOR;
}
很明显,如果我尝试更改 getCreator
的类型类(class) B
至 Creator<A>
, 不起作用,因为 Parcelable 创建者的类型是 B
.
我该如何解决这个问题?
最佳答案
我是这样实现的。我创建了一个抽象父类,让我们使用你的父类A
,你应该在其中添加两个抽象方法:
protected abstract void writeChildParcel(Parcel pc, int flags)
和protected abstract void readFromParcel(Parcel pc)
然后您需要一个静态方法来创建 A
的正确实例。在我的例子中,有一个类型属性(您可以使用 enum
)是有意义的,我可以在其中识别它们中的每一个。这样我们就可以拥有一个静态的 newInstance(int type)
方法,如下所示:
public static A newInstance(int type) {
A a = null;
switch (type) {
case TYPE_B:
a = new B();
break;
...
}
return a;
}
public static A newInstance(Parcel pc) {
A a = A.newInstance(pc.readInt()); //
//call other read methods for your abstract class here
a.readFromParcel(pc);
return a;
}
public static final Parcelable.Creator<A> CREATOR = new Parcelable.Creator<A>() {
public A createFromParcel(Parcel pc) {
return A.newInstance(pc);
}
public A[] newArray(int size) {
return new A[size];
}
};
然后,编写您的writeToParcel
如下:
public void writeToParcel(Parcel out, int flags) {
out.writeInt(type);
//call other write methods for your abstract class here
writeChildParcel(pc, flags);
}
现在摆脱 CREATOR
和 B
中的所有其他 Parcelable
方法,只实现 writeChildParcel
和 readFromParcel
在里面。你应该可以开始了!
希望对您有所帮助。
关于android - 继承人类的 getCreator 的 Parcelable 继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20018095/