自定義序列化類
- 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);