
如何使用类Intent的putExtra()方法将自定义类型的对象从一个Activity传递到另一个?
解决方法:
如果您只是传递物体,那么Parcelable就是为此设计的.它需要比使用Java的本机序列化更多的努力,但它更快(我的意思是,方式更快).
从文档中,一个如何实现的简单示例是:
// simple class that just has one member property as an examplepublic 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,只需将它们放入0700和putExtra():
Intent i = new Intent();i.putExtra("name_of_extra", myParcelableObject);然后你可以用getParcelableExtra()将它们拉出来:
Intent i = getIntent();MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");如果您的Object类实现了Parcelable和Serializable,那么请确保您执行以下 *** 作之一:
i.putExtra("parcelable_extra", (Parcelable) myParcelableObject);i.putExtra("serializable_extra", (Serializable) myParcelableObject); 总结 以上是内存溢出为你收集整理的如何使用Intents将对象从一个Android Activity发送到另一个?全部内容,希望文章能够帮你解决如何使用Intents将对象从一个Android Activity发送到另一个?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)