從Parcelable interface文檔另一個類對象的引用:
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
當實現Parcelable接口的類的對象要寫入Parcel時,調用writeToParcel(...)
。
當要使用包創建此類的對象時,將調用CREATOR.createFromParcel(Parcel in)
。從那裏開始,班級如何從包裹創建它的實例取決於班級的開發人員。在上例中,從createFromParcel(...)
方法調用構造函數private MyParcelable(Parcel in)
。
傳統上,許多開發商在它們的實現定義readFromParcel(Parcel in)
方法和構造函數調用它:
private MyParcelable(Parcel in) {
readFromParcel(in);
}
private void readFromParcel(Parcel in) {
mData = in.readInt();
}
來源
2014-08-06 03:45:51
prk
'readFromParcel'需要預先創建的對象,而'createFromParcel'直接從包裹中返回一個新實例化的對象。這是因爲,當一個'Parcelable'類型實例被用作'out'或'inout'參數時,Binder子系統在概念上首先創建一個空對象,然後在返回響應時用'readFromParcel'填充它。 – scorpiodawg