从类的某些字段在android中创建parcelable

时间:2013-08-19 14:33:59

标签: android android-intent parcelable

我有以下课程,我打算从一个活动转到另一个活动:

public class Ad extends ListItem implements parcelable{
    private String _type;
    private String _recordID;
    private String _line1;
    private String _line2;
    private String _line3;
    private String _line4;
    private String _url;
    private IOnUiNeedToUpdateListener _listener;
    private boolean _notActive = false;
    private String _alertText;
    private Double _longitude;
    private Double _latitude;
}

我想将一系列此类对象从一个活动传递到另一个活动。但是,我不需要通过所有字段。

是否可以仅从所需字段创建包裹并发送?

2 个答案:

答案 0 :(得分:2)

尝试像这样设计你的课程。

public class Form implements Parcelable {

private String formdata1;
private String formdata2;
private String formdata3;
private String formdata4;

public Form() {
}

public Form(Parcel in) {
    setFormdata1(in.readString());
    setFormdata2(in.readString());
    setFormdata3(in.readString());
    setFormdata4(in.readString());
}

public String getFormdata1() {
    return formdata1;
}

public void setFormdata1(String formdata1) {
    this.formdata1 = formdata1;
}

public String getFormdata2() {
    return formdata2;
}

public void setFormdata2(String formdata2) {
    this.formdata2 = formdata2;
}

public String getFormdata3() {
    return formdata3;
}

public void setFormdata3(String formdata3) {
    this.formdata3 = formdata3;
}

public String getFormdata4() {
    return formdata4;
}

public void setFormdata4(String formdata4) {
    this.formdata4 = formdata4;
}

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

@Override
public void writeToParcel(Parcel in, int arg1) {
    in.writeString(getFormdata1());
    in.writeString(getFormdata2());
    in.writeString(getFormdata3());
    in.writeString(getFormdata4());
}

public static final Parcelable.Creator<Form> CREATOR = new Parcelable.Creator<Form>() {

    @Override
    public Form createFromParcel(Parcel in) {
        return new Form(in);
    }

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

};

}

答案 1 :(得分:1)

这是您的代码写入Parcel以及您的代码从Parcel读取。基本上yes。你可以写任何你想要的东西。所有成员的内容,某些成员的内容,没有成员,但用于恢复对象状态的其他值等等。