Android(安卓)通过Intent 传递对象
16lz
2021-01-26
If you're just passing objects around then Parcelable was designed for this. It requires a little more effort to use than using Java's native serialization, but it's way faster (and I mean way,WAY faster).
From the docs, a simple example for how to implement is:
// 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 public int describeContents() { return 0; } // write your object's data to the passed-in Parcel 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(); } }
Once you have your objects implement Parcelable
it's just a matter of putting them into yourIntents with putExtra():
Intent i = new Intent(); i.putExtra("name_of_extra", myParcelableObject);
Then you can pull them back out with getParcelableExtra():
Intent i = getIntent(); MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer