如果您只是传递对象,那么Parcelable就是为此而设计的。与使用Java的本机序列化相比,使用它需要付出更多的努力,但是它的速度更快(我的意思是,WAY更快)。
在文档中,有关如何实现的一个简单示例是:
// simple class that just has one member property as an examplepublic class MyParcelable implements Parcelable { private int mData; // 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);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)