Android 使用Parcelable接口

package com.example.AndroidStudy;
import android.os.Parcel;
import android.os.Parcelable;
public class Person  implements Parcelable{
  private String name;
  private   int age;
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  //重写下面两个方法
  @Override
  public int describeContents() {
    return 0;
  }
  @Override
  public void writeToParcel(Parcel dest, int flags) {
    //把数据写入Parcel
    dest.writeString(name);
    dest.writeInt(age);
  }
  //还必须含有一个名称为CREATOR的静态成员,该成员对象要求实现Parcelable.Creator接口及其方法
  public static final  Creator<Person>CREATOR=new Creator<Person>() {
    @Override
    public Person createFromParcel(Parcel source) {
      //读取时返回Person对象---根据Parcel写入的数据生成Person返回
      return new Person(source.readString(), source.readInt());
    }
    @Override
    public Person[] newArray(int size) {
      return new Person[size];
    }
  };
}

使用 Bundle.putParcelable()方法把自定义Person数据放入Bundle内
Intent intent1=new Intent(MyActivity.this,SecondActivity.class);
Bundle bundle=new Bundle();
bundle.putString("title","Activity 2");
bundle.putParcelable("person",new Person("小白",20));
intent1.putExtras(bundle);
startActivity(intent1);

//获取bundle数据
 Bundle bundle=getIntent().getExtras();
 String text=bundle.getString("title");//根据key来获取
 Person person=(Person)bundle.getParcelable("person");







你可能感兴趣的:(Android 使用Parcelable接口)