How can I pass an object of a custom type from one Activity to another using the
putExtra()
method of the class Intent?
最佳答案
如果您只是传递对象,那么 Parcelable是为此而设计的。使用它比使用 Java 的 native 序列化需要更多的努力,但它更快(我的意思是,WAY 更快)。
从文档中,如何实现的一个简单示例是:
// simple class that just has one member property as an example
public class MyParcelable implements Parcelable {
private int mData;
/* everything below here is for implementing Parcelable */
// 99.9% of the time you can just ignore this
@Override
public int describeContents() {
return 0;
}
// write your object's data to the passed-in Parcel
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
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];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
请注意,如果您要从给定的 Parcel 中检索多个字段,则必须按照放入它们的顺序(即采用 FIFO 方法)执行此操作。
一旦你的对象实现了Parcelable
,只需将它们放入你的Intents与 putExtra() :
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
然后你可以用 getParcelableExtra() 把它们拉回来。 :
Intent i = getIntent();
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");
如果您的 Object Class 实现 Parcelable 和 Serializable,请确保您确实转换为以下之一:
i.putExtra("parcelable_extra", (Parcelable) myParcelableObject);
i.putExtra("serializable_extra", (Serializable) myParcelableObject);
关于android - 如何使用 Intents 将对象从一个 Android Activity 发送到另一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2139134/