在您的自定義對象落實Parcelable
接口,並通過Intent
發送。
下面是一個Parcelable
對象的示例。
public class MyObject implements Parcelable {
private String someString = null;
private int someInteger = 0;
public MyObject() {
// perform initialization if necessary
}
private MyObject(Parcel in) {
someString = in.readString();
someInteger = in.readInt();
}
public static final Parcelable.Creator<MyObject> CREATOR =
new Parcelable.Creator<MyObject>() {
@Override
public MyObject createFromParcel(Parcel source) {
return new MyObject(source);
}
@Override
public MyObject[] newArray(int size) {
return new MyObject[size];
}
};
// Getters and setters
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(someString);
dest.writeInt(someInteger);
}
}
這是發生了什麼事。如果實現Parcelable
接口,則必須創建一個以Parcel
作爲參數的私有構造函數。 Parcel
保存所有的序列化值。
您必須實現名爲CREATOR
的嵌套類Parcelable.Creator
,因爲這將在Android重新創建對象時被調用。
方法describeContents()
只適用於特殊情況。您可以保留它,因爲它的返回值爲0
。
有趣的行爲發生在writeToParcel()
,你的名字告訴你,你的數據寫入一個Parcel
對象。
現在,您可以直接將自定義對象直接添加到Intent
(如本例中)。
MyObject myObject = new MyObject();
Intent i = new Intent();
i.setExtra("MY_OBJECT", myObject);
// implicit or explicit destination declaration
startActivity(i);
那麼這真的很好的解釋,但我使用Parcelable和應用程序類之間混淆,所以你有什麼建議? – Hunt
我想它很大程度上取決於用例,但在你的情況下,我會推薦'Parcelables'。 –
好的,因爲我有一個非常沉重的數據使用量,所以我會去與parcelables。 – Hunt