我正在尝试在 Android
上的 Activities
之间传递数据 (ArrayList
)
当实现 Parcelable
的类不包含自定义对象(商店)时一切正常,但如果我的类包含自定义对象,我该怎么办?
购物
public Shop(Parcel in) {
this.id = in.readString();
this.name = in.readString();
this.type = in.readString();
this.lat= in.readDouble();
this.long= in.readDouble();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeString(this.name);
dest.writeString(this.type);
dest.writeDouble(this.lat);
dest.writeDouble(this.long);
}
@SuppressWarnings("rawtypes")
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Shop createFromParcel(Parcel in) {
return new Shop(in);
}
public Shop[] newArray(int size) {
return new Shop[size];
}
};
这是我的另一个类 Offer,它包含一个 Shop 对象
public Offer(Parcel in) {
this.id = in.readInt();
this.title = in.readString();
this.myShop = in.read.......();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeString(this.title);
dest.write......(this.myShop);
}
我应该读写哪种数据类型?
非常感谢!
最佳答案
您的Shop
类应该实现Parcelable
并且您应该使用
public Offer(Parcel in) {
this.id = in.readInt();
this.title = in.readString();
this.myShop = in.readParcelable(Shop.class.getClassLoader());
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeString(this.title);
dest.writeParcelable(this.myShop, flags);
}
关于java - 包含自定义对象的 Parcelable 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21551167/