使用parcelable传递自定义类对象

时间:2017-11-17 03:45:32

标签: android parcelable parcel

如何在实现parcelable

的类中访问自定义类对象

我有一个parcelable类作为folows

class A implements Parcelable{
      private CustomClass B;
}

是否可以在 writeToParcel() readParcel(Parcel in)

期间将该自定义类用作常规变量

PS:我不能像在非Android模块中那样在B类上实现parcelable

2 个答案:

答案 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());
    }
}