我無法弄清楚從包裹寫入/讀取時如何使用polymorohism。 我知道我需要在基類中實現Parcelable,並且還需要在所有派生類中實現Parcelable(如果子類具有其他屬性,我希望將其寫入宗地)。 什麼我不明白,我不知道是否甚至可能是 - 如何從Parcelable中讀取子類,即如何知道我從包中讀取哪種子類。 我可以做一些破解,像寫一些指示器到包裹中,告訴我使用什麼類的裝載器,但我認爲會有一些更優雅的方式,否則沒有多少使用多態。Android - 多態和可編輯
爲了說明我的問題,讓說我有類是這樣的:
Shape.class
public class Shape implements Parcelable {
public float area;
public Shape() {
}
public Shape(Parcel in) {
area = in.readFloat();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeFloat(area);
}
//CREATOR etc..
}
RectangleShape.class
public class RectangleShape extends Shape {
float a;
float b;
public RectangleShape(Parcel in) {
super(in);
a = in.readFloat();
b = in.readFloat();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeFloat(area);
dest.writeFloat(a);
dest.writeFloat(b);
}
//CREATOR etc..
}
CircleShape.class
public static class CircleShape extends Shape {
float r;
public CircleShape(Parcel in) {
super(in);
r = in.readFloat();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeFloat(area);
dest.writeFloat(r);
}
//CREATOR etc..
}
現在,在一些其他類我有這樣的事情:
public class Geometry implements Parcelable {
Shape myShape;
public Geometry (boolean condition) {
if (condition)
myShape = new CircleShape(4.5);
else
myShape = new RectangleShape(3.4, 3.5);
}
@Override
public Geometry(Parcel in) {
in.readParcelable(??? - **how do I know what class loader to put here?**)
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(myShape,flags);
}
//CREATOR etc..
}
有什麼辦法,編寫成包裹它是什麼子類時,沒有實例類型的隱式檢查,我可以「告訴」機器人?
我有類似的問題。就我而言,基類是一個界面,使事情變得更容易。我想我解決它的方法是在接口中擴展Parcelable(我們稱之爲「Foo」),然後在其子類中實現了'Foo',因此也實現了'Parcelable'。我不確定這是否有幫助... –
我從來沒有實現可擴展的擴展,但我想一個好的建議是檢查谷歌自己如何做到這一點。 AbsSavedState是一個包含多個子類的Parcelable類。這裏是它的源代碼https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/view/AbsSavedState.java和View.BaseSavedState https: //android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/view/View.java#22556 – Budius