Передача пользовательских объектов класса с использованием parcelable

Как я могу получить доступ к объекту пользовательского класса в классе, реализующем parcelable?

У меня есть класс посылки

class A implements Parcelable{
      private CustomClass B;
}

Можно ли использовать этот пользовательский класс в качестве нормальной переменной во время writeToParcel() а также readParcel(Parcel in)

PS: я не могу реализовать parcelable в классе B, как это происходит в модуле, отличном от Android

2 ответа

Решение

В своем комментарии вы говорите, что 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());
    }
}

Сначала нужно сделать CustomClassparcelable как в

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конвертировать класс как Json String с помощью Google 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
    }
}
Другие вопросы по тегам