如何使用其中包含 Builder
模式的类来实现 Parcelable
?
public class Leave implements Parcelable {
private final String id;
private final String type;
private final String status;
private final String approver;
public static class Builder {
private String id;
private String type;
private String status;
private String approver;
public Builder id(String id) { this.id = id; return this; }
public Builder type(String type) { this.type = type; return this; }
public Builder status(String status) { this.status = status; return this; }
public Builder approver(String approver) { this.approver = approver; return this; }
public Leave build() {
return new Leave(this);
}
}
private Leave(Builder builder) {
this.id = builder.id;
this.type = builder.type;
this.status = builder.status;
this.approver = builder.approver;
}
public String getId() {
return id;
}
public String getType() {
return type;
}
public String getStatus() {
return status;
}
public String getApprover() {
return approver;
}
public static final Parcelable.Creator<Leave> CREATOR = new Parcelable.Creator<Leave>() {
public Leave createFromParcel(Parcel in) {
return new Leave(in); // ERROR! Leave(Parcel) is undefined
} // Builder has a private constructor leaving
// a single instance;
public Leave[] newArray(int size) {
return new Leave[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(type);
dest.writeString(status);
dest.writeString(approver);
}
}
最佳答案
你需要添加包裹部分,实现这个:
public Leave(Parcel in)
{
this.id = in.readString();
this.type = in.readString();
this.status = in.readString();
this.approver = in.readString();
}
关于java - 如何使用 Builder 模式将 Parcelable 实现到一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21397106/