继承类的getCreator的Parcelable继承问题

时间:2013-11-16 11:52:42

标签: android parcelable

我有一个可扩展的课程AB,其范围为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的{​​{1}}类型更改为B,则显然不起作用,因为Parcelable创建者的类型为Creator<A>。< / p>

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

以下是我实现此方法的方法。我创建了一个抽象的父类,让我们使用你的父类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中的Parcelable和所有其他B方法,并在其中实施writeChildParcelreadFromParcel。你应该好好去!

希望它有所帮助。