63

我得到了一个 Parcelable 的实现,它适用于不涉及继承的单个类。当涉及到继承时,我在找出实现接口的最佳方法时遇到了问题。假设我得到了这个:

public abstract class A {
    private int a;
    protected A(int a) { this.a = a; }
}

public class B extends A {
    private int b;
    public B(int a, int b) { super(a); this.b = b; }
}

问题是,这是为 B 实现 Parcelable 接口的推荐方法(在 A 中?在他们两个中?如何?)

4

3 回答 3

84

这是我最好的解决方案,我很高兴听到有人对此有所考虑。

public abstract class A implements Parcelable {
    private int a;

    protected A(int a) {
        this.a = a;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(a);
    }

    protected A(Parcel in) {
        a = in.readInt();
    }
}

public class B extends A {
    private int b;

    public B(int a, int b) {
        super(a);
        this.b = b;
    }

    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();
    }
}
于 2010-10-29T19:59:25.217 回答
4

这是我的变种。我认为这很好,因为它非常清楚地显示了虚拟读写方法之间的对称性。

旁注:我认为 Google 在设计 Parcelable 界面方面做得很差。

public abstract class A implements Parcelable {
    private int a;

    protected A(int a) {
        this.a = a;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(a);
    }

    public void readFromParcel(Parcel in) {
        a = in.readInt();
    }
}

public class B extends A {
    private int b;

    public B(int a, int b) {
        super(a);
        this.b = b;
    }

    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);
    }

    public void readFromParcel(Parcel in) {
        super(in);
        b = in.readInt();
    }
}
于 2016-06-22T15:36:26.860 回答
1

这是 A 类在现实世界设置中的实现,因为 B 类可能有多个具有除 int 之外的不同类型的对象

它使用反射来获取类型。然后使用排序函数对字段进行排序,以便读取和写入以相同的顺序发生。

https://github.com/awadalaa/Android-Global-Parcelable

于 2013-09-27T20:13:18.753 回答