[英]How to use Parcelable for a class which has multiple constructors?
好吧,我試圖將對象的數組列表從一個活動傳遞到另一個活動。 我在學生類中有 2 個構造函數。 如果,我使用,Serializable 比代碼如下:
@SuppressWarnings("serial")
public class Student implements Serializable
{
private int studentdID;
private String studentName;
private String studentDept;
public Student(){}
public Student(String name, String dpt)
{ this.studentName = name;
this.studentDept = dpt;}
public Student(int id, String name, String dpt)
{ this.studentdID = id;
this.studentName = name;
this.studentDept = dpt; }
public int getstudentdID() { return studentdID; }
public void setstudentdID(int studentdID) {this.studentdID = studentdID;}
public String getstudentName() { return studentName;}
public void setstudentName(String studentName) {this.studentName = studentName;}
public String getstudentDept() { return studentDept; }
public void setstudentDept(String studentDept) { this.studentDept = studentDept;}
}
但我面臨的問題是,我將如何用 Parcelable 做到這一點? 我將如何像使用 Serializable 那樣在類中設置變量的值? 我的意思是分別使用 2 個構造函數 - 一個沒有 ID 另一個沒有 ID?
你讀過 Parcelable 是如何工作的嗎?
您只需要使用一個parcelable constrcutor閱讀您傳遞給它什么, Parcelable
接口將添加一個方法writeToParcel
你把數據保存。
這不是像Serializable
這樣的自動過程,一切都取決於您。
Parcelable
將使用的構造函數將只接受一個參數Parcel
,您將在其中找到一些方法,例如read*(KEY)
來讀回值。
在writeToParcel
您將在Parcel
(方法的參數)中write*(KEY, VALUE)
要通過write*(KEY, VALUE)
傳遞的write*(KEY, VALUE)
。
Parcelable
不關心您的構造函數或字段。
PS 你也需要一個CREATOR
。 如果需要,請在線閱讀一些教程以了解更多信息。
Marco 的回答解釋了為什么 Parcelable 不會自動決定使用什么構造函數——它不能。
但是,有一種方法可以解決這個問題。 使用Parcel.dataAvail()
,其中
返回要從包裹中讀取的剩余數據量。 即,dataSize()-dataPosition()。
例如,
public Student(){}
public Student(String name, String dpt)
{
this.studentName = name;
this.studentDept = dpt;}
public Student(int id, String name, String dpt)
{ this.studentdID = id;
this.studentName = name;
this.studentDept = dpt;
}
public Student(Parcel in) {
name = in.readString();
dpt = in.readString();
if(in.dataAvail() > 0) // is there data left to read?
id = in.readInt();
}
^ 上述構造函數將允許正確實例化必要的變量。 此外,您定義writeToParcel()
類似於:
public void writeToParcel(Parcel out) {
out.writeString(name);
out.writeString(dpt);
//0 is the default value of id if you didn't initialize it like
// in the first constructor. If it isn't 0, that means it was initialized.
if(id != 0)
out.writeInt(id);
}
當然,您需要像這樣定義您的CREATOR
:
public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
public Student createFromParcel(Parcel in) {
return new Student(in);
}
public Student[] newArray(int size) {
return new Student[size];
}
};
@u3l 解決方案不是必需的..有多少構造函數並不重要。 很簡單,它可以像正常實現一樣工作。 我的意思是當 Parcelable 中存在多個構造函數時不需要特別小心。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.