gpt4 book ai didi

java - 我应该如何将 Parcelable 用于抽象类?

转载 作者:行者123 更新时间:2023-11-30 10:56:38 25 4
gpt4 key购买 nike

在我的 Android 应用程序中,我基本上有一个实现 Parcelable 的类,其中一个需要从 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 并不意味着要成为序列化的通用工具,但它似乎对很多应用程序来说都是一个重要问题,并且非常有必要获得 Parcelables 在用户按下后退按钮然后想要返回应用程序的情况下工作,因为需要保存应用程序的状态。我在 AbstractClass1 上的特殊 CREATOR 也不起作用,因为此类不应该知 Prop 体实现。它应该是某种工厂模式吗?

最佳答案

writeParcelable(Parcelable, int) 方法将适当的非抽象类的名称写入 Parcel(以及您在 writeToParcel 方法)。

与此相反的是 readParcelable(null)readParcelable 首先读回类的名称,然后在调用 CreatorcreateFromParcel 方法。

readParcelable 的参数不是Class,而是ClassLoader。如果您传递 null,则使用默认的 ClassLoader

关于java - 我应该如何将 Parcelable 用于抽象类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32941456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com