Parcelable序列化方法
Android Studio是个强大的编译器,我们只需要让想要实现Parcelable序列化的对象实现Parcelable接口,然后按照编译器的报错提示一步步自动生成代码即可。
没错,一行代码都不需要写!
Parcelable序列化示例
/**
* 直接实现Parcelable接口,代码按编译器提示自动生成即可。
*/
public class Person implements Parcelable {
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
protected Person(Parcel in) {
name = in.readString();
age = in.readInt();
}
public static final Creator<Person> CREATOR = new Creator<Person>() {
@Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
}