在您的自定义对象落实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