问题
I have a parcelable class A
and B
that extends A
Example:
The class 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();
}
}
The heir class 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();
}
}
In B I get the error "the return type is incompatible with A.getCreator()" in
public static Creator<B> getCreator() {
return CREATOR;
}
clearly if I try to change the type of getCreator
of the class B
to Creator<A>
, doesn't work because the type of Parcelable creator is B
.
how could I solve this issue?
回答1:
Here is how I implemented this. I created an abstract parent class, lets use your parent class A
, where you should add two abstract methods:
protected abstract void writeChildParcel(Parcel pc, int flags)
and protected abstract void readFromParcel(Parcel pc)
Then you need a static method to create the right instance of A
. In my case it made sense to have a type attribute (you can use an enum
) where I could identify each of them. This way we can have a static newInstance(int type)
method like so:
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];
}
};
Then, write your writeToParcel
as follows:
public void writeToParcel(Parcel out, int flags) {
out.writeInt(type);
//call other write methods for your abstract class here
writeChildParcel(pc, flags);
}
Now get rid of your CREATOR
and all other Parcelable
methods in B
and just implement writeChildParcel
and readFromParcel
in it. You should be good to go!
Hope it helps.
来源:https://stackoverflow.com/questions/20018095/parcelable-inheritance-issue-with-getcreator-of-heir-class