簡體   English   中英

我應該如何將 Parcelable 用於抽象類?

[英]How should I use Parcelable for abstract classes?

在我的 Android 應用程序中,我基本上有一個實現Parcelable類,其中一個需要從Parcel讀取和寫入Parcel字段是對也實現Parcelable的抽象類的引用。

這是抽象類及其具體實現之一:

public abstract AbstractClass1 implements Parcelable {
}

public class ConcreteClass1 extends AbstractClass1 {
    private ConcreteClass1(Parcel in) {
        this.setSomeData(in.readInt());
    }

    public static final Parcelable.Creator<ConcreteClass1> CREATOR =
        new Parcelable.Creator<ConcreteClass1>() {
            public ConcreteClass1 createFromParcel(Parcel in) {
                return new ConcreteClass1 (in);
            }

            public ConcreteClass1[] newArray(int size) {
                return new ConcreteClass1[size];
            }
        };

    @Override
    public int describeContents() { return 0; }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.getSomeData());
    }
}

到目前為止,這是我對其他Parcelable類所擁有的,該類需要將AbstractClass1的引用讀取和寫入其Parcel 我不確定如何使CREATOR工作:

public Class2 implements Parcelable {
    private int data = 42;
    private AbstractClass1 class1;

    public Class2(AbstractClass1 c) { this.class1 = c; }

    private Class2(Parcel in) {
        this.data = in.readInt();

        // this line is bad since it requires us to know about
        // what concrete class is being set for class1.  This
        // class should only need to be aware of AbstractClass1
        this.class1 = in.readParcelable(ConcreteClass1.class);
    }

    public static final Parcelable.Creator<Class2> CREATOR =
        new Parcelable.Creator<Class2>() {
            public Class2 createFromParcel(Parcel in) {
                return new Class2(in);
            }

            public Class2[] newArray(int size) {
                return new Class2[size];
            }
        };

    @Override
    public int describeContents() { return 0; }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.data);
        dest.writeInt(this.class1);
    }
}

是否有關於如何使用Parcelable處理這個抽象類問題的最佳實踐? 我知道Parcelable並不是用於序列化的通用工具,但它似乎對許多應用程序來說這將是一個重要問題,並且在用戶按下后退按鈕的情況下讓Parcelable工作至關重要然后想返回到應用程序,因為需要保存應用程序的狀態。 我在AbstractClass1上的特殊CREATOR也不起作用,因為這個類不應該知道具體的實現。 它應該是某種工廠模式嗎?

方法writeParcelable(Parcelable, int)將適當的非抽象類的名稱寫入Parcel (以及您在writeToParcel方法中寫入的數據)。

與此相反的是readParcelable(null) readParcelable首先讀取類的名稱,以便在調用CreatorcreateFromParcel方法之前從該類中獲取正確的Creator對象。

readParcelable的參數不是Class而是ClassLoader 如果傳遞null ,則使用默認的ClassLoader

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM