自定义序列化类
- public class Contacts implements Parcelable {
- public static final String PARCELABLE_KEY = "aliusa.cn.ui.Contacts.parcelableKey";
- private int id;
- private String name;
- public Contacts(int id,String name){
- this.name = name;
- this.id = id;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- @Override
- public int describeContents() {
- return 0;
- }
- //实现Parcelable的方法writeToParcel,将Contacts序列化为一个Parcel对象
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(id);
- dest.writeString(name);
- }
- //实例化静态内部对象CREATOR实现接口Parcelable.Creator
- public static final Parcelable.Creator<Contacts> CREATOR = new Parcelable.Creator<Contacts>() {
- //将Parcel对象反序列化为Contacts
- public Contacts createFromParcel(Parcel in) {
- return new Contacts(in);
- }
- public Contacts[] newArray(int size) {
- return new Contacts[size];
- }
- };
- //关键的事
- private Contacts(Parcel in) {
- id = in.readInt();
- name = in.readString();
- }
- }
- 传递参数
- Contacts contact = new Contacts("0001", "aliusa");
- Bundle bundle = new Bundle();
- bundle.putParcelable(Contacts.PARCELABLE_KEY , contact);
- intent.putExtra(parcelableKey, contact);
- 读取参数
- final Contacts contact = (Contacts) getIntent().getExtras().getParcelable(Contacts.PARCELABLE_KEY);