使用 Parcelable 传递自定义类对象

0x5*_*368 1 android parcel parcelable

我如何访问实现 Parcelable 的类中的自定义类对象

我有一个可分割的类,如下

class A implements Parcelable{
      private CustomClass B;
}
Run Code Online (Sandbox Code Playgroud)

writeToParcel()是否可以在期间和期间使用该自定义类作为普通变量readParcel(Parcel in)

PS:我无法在 B 类上实现 Parcelable,因为它是在非 Android 模块中

raj*_* ks 7

首先你需要让你CustomClass parcelable

class CustomClass implements Parcelable{
   // write logic to write and read from parcel
}
Run Code Online (Sandbox Code Playgroud)

然后,在你的班级里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
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

如果您无法制作CustomClassas ,请使用 googleParcelable将类转换为并将其写入并在读取时读取并转换回Json StringgsonParcelStringobject

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
    }
}
Run Code Online (Sandbox Code Playgroud)