//將實體類序列化以下: //有兩種方法:1,實現Serializable 2.實現parcelable要重寫裏面的方法 public class Person implements Serializable,Parcelable{ private String name; private int age; private boolean isMarried; public Person(String name, int age, boolean isMarried) { super(); this.name = name; this.age = age; this.isMarried = isMarried; } public Person() { super(); } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", isMarried=" + isMarried + "]"; } /*經過實現Parcelable接口序列化對象的步驟: 一、聲明實現接口Parcelable 二、實現Parcelable的方法writeToParcel,將你的對象序列化爲一個Parcel對象 三、實例化靜態內部對象CREATOR實現接口Parcelable.Creator: 其中public static final一個都不能少,內部對象CREATOR的名稱也不能改變,必須所有大寫。 四、完成CREATOR的代碼,實現方法createFromParcel,將Parcel對象反序列化爲你的對象 */ @Override public int describeContents() { //這個能夠不用理 return 0; } //1.寫操做//序列化方法 @Override public void writeToParcel(Parcel dest, int flags) { //經過這個方法把對象序列化成Parcel,可理解爲把你的對象寫到流裏面 dest.writeString(name); dest.writeInt(age); //boolean寫比較特殊一些,要建立一個數組 dest.writeBooleanArray(new boolean[]{isMarried}); } //2.建立一個私有構造方法做反序列化,注意讀和寫的順序要一致 private Person(Parcel source){ this.name=source.readString(); this.age=source.readInt(); //boolean讀也比較特殊一些,要建立一個數組 boolean[]b=new boolean[1]; source.readBooleanArray(b); this.isMarried=b[0]; } /*3.實例化靜態內部對象CREATOR實現接口Parcelable.Creator: 其中public static final一個都不能少,內部對象CREATOR的名稱也不能改變,必須所有大寫。 <>裏面寫的是你的對象實體類 */ public static final Parcelable.Creator<Person>CREATOR=new Parcelable.Creator<Person>() { @Override public Person createFromParcel(Parcel source) { //把Parcel反序列爲你的對象,可理解爲從流中讀取對象 return new Person(source); } @Override public Person[] newArray(int size) { return new Person[size]; } }; } //序列化傳輸代碼,傳給另一個頁面Activiyty public void send_object(View view){ //傳輸序列化 Intent intent=new Intent(this,SerializableObject.class); Person person=new Person("張三",23,false); Bundle bundle=new Bundle(); //第一種:實現Serializable方法 //bundle.putSerializable("person", person);//實現序列化接口後,bundle能夠直接傳遞序列化對象 //第二種:實現Parcelable bundle.putParcelable("person", person); intent.putExtras(bundle); startActivity(intent); /*不須要返回數據時使用這個startActivity(),有數據回傳時用 這個startActivityForResult(intent, requestCode);且要重寫onActivityResult()回傳方法處理數據*/ } //在另一個頁面接收的代碼 text_next=(TextView) this.findViewById(R.id.text_next); Intent intent=getIntent();//獲取點擊到本頁面的意圖 Bundle bundle=intent.getExtras(); //這是第一種實現Serializable方法接收 //Person person=(Person) bundle.getSerializable("person"); //第二種:實現Parcelable接收 Person person=bundle.getParcelable("person"); text_next.setText(person.toString());