使用 parcelable 传递自定义 class 对象

Passing custom class objects using parcelable

如何在 class 实现 parcelable

中访问自定义 class 对象

我有一个包裹class如下

class A implements Parcelable{
      private CustomClass B;
}

是否可以在 writeToParcel()readParcel(Parcel in)[= 期间将自定义 class 用作普通变量25=]

PS:我无法在 class B 上实现 parcelable,因为它在非 Android 模块中

首先你需要让你的 CustomClass parcelable

class CustomClass implements Parcelable{
   // write logic to write and read from parcel
}

然后,在你的 class 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 gson将class转换为Json String并将其写入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
    }
}

在您的评论中,您说 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());
    }
}