可打包自定义对象的问题 - Android

我正在尝试将自定义对象从一个活动传递到另一个活动。我发现我们可以使用 bundle 将数据传递到 Intent 中,并且我们需要在我们的类中实现一个 Parcelable 接口。


在下面的代码中,我删除了无用的东西。


public class TravelCard implements Parcelable {


public static final Creator<TravelCard> CREATOR = new Creator<TravelCard>() {

    @Override

    public TravelCard createFromParcel(Parcel in) {

        return new TravelCard(in);

    }


    @Override

    public TravelCard[] newArray(int size) {

        return new TravelCard[size];

    }

};

private String travelTitle, travelCountry, dateRange, numOfPerson;

private List<TravelDay> days;


protected TravelCard(Parcel in) {

    travelTitle = in.readString();

    travelCountry = in.readString();

    dateRange = in.readString();

    numOfPerson = in.readString();

    in.readTypedList(days, TravelDay.CREATOR);

}


@Override

public int describeContents() {

    return 0;

}


@Override

public void writeToParcel(Parcel dest, int flags) {

    dest.writeString(this.travelTitle);

    dest.writeString(this.travelCountry);

    dest.writeString(this.dateRange);

    dest.writeString(this.numOfPerson);

    dest.writeTypedList(this.days);

}

在这个类中,我有另一个自定义对象的列表:


public class TravelDay implements Parcelable {


public static final Creator<TravelDay> CREATOR = new Creator<TravelDay>() {

    @Override

    public TravelDay createFromParcel(Parcel in) {

        return new TravelDay(in);

    }


    @Override

    public TravelDay[] newArray(int size) {

        return new TravelDay[size];

    }

};


public int current_day;

private String title, note, dateOfToday;


protected TravelDay(Parcel in) {

    title = in.readString();

    note = in.readString();

    dateOfToday = in.readString();

    current_day = in.readInt();

}


@Override

public int describeContents() {

    return 0;

}


@Override

public void writeToParcel(Parcel dest, int flags) {

    dest.writeString(title);

    dest.writeString(note);

    dest.writeString(dateOfToday);

    dest.writeInt(current_day);

}

我认为直到这里一切都应该没问题。


潇潇雨雨
浏览 140回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java