下面的这段话摘自Parcelable的文档:
Interface for classes whose instances can be written to and restored from a Parcel
. Classes implementing the Parcelable interface must also have a static field called CREATOR
, which is an object implementing the Parcelable.Creator
interface.
从典型来看,实现该接口需要实现2个接口,writeToParcel(Parcel dest, int flags)和describeContents()。除此之外,还必须新建一个含有 Creator的属性。典型的用法如下:
public class User implements Parcelable{
private String name;
private String email;
private int age;
public User(String name, String email, int age) {
this.name = name;
this.email = email;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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) {
Bundle bundle = new Bundle();
bundle.putString("name", getName());
bundle.putString("email", getEmail());
bundle.putInt("age", getAge());
dest.writeBundle(bundle);
}
public static final Creator<User> CREATOR = new Creator<User>() {
@Override
public User createFromParcel(Parcel source) {
Bundle bundle = source.readBundle();
return new User (bundle.getString("name"), bundle.getString("email"), bundle.getInt("age"));
}
@Override
public User[] newArray(int size) {
return new User[size];
}
};
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", age=" + age +
'}';
}
}
如果碰到readBundle: bad magic number的错误,请检查是否多次使用source.readBundle()来读取同一个内容,第二次调用将会返回异常。