如何使用自己的对象和枚举进行 parcelable class

How to parcelable class with own objects and enums

我有 class 关税,我需要打包它。

public class Tariff implements Parcelable{

private String operator;
private Discounts discount;
private boolean unlimited;
private Billings billing;
private String name;
private double price;
private double calculated;
private Call call;
private Sms sms;

我在这里找到了一些建议,但我不确定我的建议是否正确。 1)对于可打包的枚举,我发现了这个。我的枚举的所有值都可以打包吗?或者我应该怎么做?

  try {
        type = Discounts.valueOf(in.readString());
    } catch (IllegalArgumentException x) {
        type = null;
    }

2) 对于可打包的另一个对象(例如调用),我发现:如果 CategoryDate class 是您的一个,您也可以将其设为可打包。然后在您的 class' writeToParcel() 调用中,您可以调用 this.date.writeToParcel() 并将相同的 Parcel 对象传递给它。这将导致 CategoryDate class 将其数据写入 CloseItPending 使用的同一个 Parcel 对象。 但我不确定我做对了。我应该怎么做?

Parcelable 样板文件真的很多,手动编码,很容易出错。

使用这个网站:http://www.parcelabler.com/

此工具自动为您的 class 生成可打包字段。请记住将 类 声明为 class 变量也可以打包。

结果会是这样的:

public class Tariff implements Parcelable {

private String operator;
private Discounts discount;
private boolean unlimited;
private Billings billing;
private String name;
private double price;
private double calculated;
private Call call;
private Sms sms;

    protected Tariff(Parcel in) {
        operator = in.readString();
        discount = (Discounts) in.readValue(Discounts.class.getClassLoader());
        unlimited = in.readByte() != 0x00;
        billing = (Billings) in.readValue(Billings.class.getClassLoader());
        name = in.readString();
        price = in.readDouble();
        calculated = in.readDouble();
        call = (Call) in.readValue(Call.class.getClassLoader());
        sms = (Sms) in.readValue(Sms.class.getClassLoader());
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(operator);
        dest.writeValue(discount);
        dest.writeByte((byte) (unlimited ? 0x01 : 0x00));
        dest.writeValue(billing);
        dest.writeString(name);
        dest.writeDouble(price);
        dest.writeDouble(calculated);
        dest.writeValue(call);
        dest.writeValue(sms);
    }

    @SuppressWarnings("unused")
    public static final Parcelable.Creator<Tariff> CREATOR = new Parcelable.Creator<Tariff>() {
        @Override
        public Tariff createFromParcel(Parcel in) {
            return new Tariff(in);
        }

        @Override
        public Tariff[] newArray(int size) {
            return new Tariff[size];
        }
    };
}