如何在实现parcelable
的类中访问自定义类对象我有一个parcelable类作为folows
class A implements Parcelable{
private CustomClass B;
}
是否可以在 writeToParcel()
和 readParcel(Parcel in)
PS:我不能像在非Android模块中那样在B类上实现parcelable
答案 0 :(得分:2)
首先,您需要将您的CustomClass
parcelable
设为
class CustomClass implements Parcelable{
// write logic to write and read from parcel
}
然后,在您的班级A
class A implements Parcelable{
private CustomClass B;
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(B, flags); // saving object
}
private A(Parcel in) {
this.B= in.readParcelable(CustomClass.class.getClassLoader()); //retrieving from parcel
}
}
修改强>
如果您无法将CustomClass
设为Parcelable
,请使用Google Json String
将课程转换为gson
并将其写入Parcel
并在阅读时,阅读String
并转换回object
class A implements Parcelable{
private CustomClass B;
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(new Gson().toJson(B), flags); // saving object
}
private A(Parcel in) {
this.B= new Gson().fromJson(in.readString(),CustomClass.class); //retrieving string and convert it to object and assign
}
}
答案 1 :(得分:1)
在评论中,您说CustomClass
由4个整数变量组成。因此,您可以这样做:
class A implements Parcelable {
private CustomClass B;
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(B.getFirst());
dest.writeInt(B.getSecond());
dest.writeInt(B.getThird());
dest.writeInt(B.getFourth());
}
private A(Parcel in) {
B = new CustomClass();
B.setFirst(dest.readInt());
B.setSecond(dest.readInt());
B.setThird(dest.readInt());
B.setFourth(dest.readInt());
}
}