如何使用Intent类的方法将自定义类型的对象从一个Activity传递到另一个Activity?putExtra()
Activity
putExtra()
如果您只是传递对象,那么Parcelable就是为此而设计的。与使用Java的本机序列化相比,使用它需要付出更多的努力,但是它的速度更快(我的意思是,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(); } }
请注意,如果要从给定的宗地中检索多个字段,则必须按照将其放入的相同顺序(即,采用FIFO方法)进行操作。
一旦实现Parcelable了对象,只需使用putExtra()将它们放入您的Intent中即可:
Intent i = new Intent(); i.putExtra("name_of_extra", myParcelableObject);
然后,您可以使用getParcelableExtra()将它们拉出:
Intent i = getIntent(); MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra"); 如果您的对象类实现了Parcelable和Serializable,则请确保将其强制转换为以下之一: i.putExtra("parcelable_extra", (Parcelable) myParcelableObject); i.putExtra("serializable_extra", (Serializable) myParcelableObject);