看例子
class Shape implements Parcelable {
public int left;
public int top;
public int width;
public int height;
// CREATOR part is omitted
protected Shape(Parcel in) {
readFromParcel(in);
}
public void readFromParcel(Parcel in) {
left = in.readInt();
top = in.readInt();
width = in.readInt();
height = in.readInt();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(left);
out.writeInt(top);
out.writeInt(width);
out.writeInt(height);
}
}
子类:
class RoundedRectangle extends Rectangle {
public int radius;
// CREATOR part is omitted
protected RoundedRectangle(Parcel in) {
super(in);
}
public void readFromParcel(Parcel in) {
super.readFromParcel(in);
radius = in.readInt();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(radius);
}
}
注意事项:
- 只有父类需要 implements Parcelable
- 只有父类需要实作 describeContents() 方法
- 如果子类没有增加其他的成员,则可以不用实作那些 parceling 的方法
- 写入/读出顺序要写正确。如果父类先写,则父类要先读,如果子类先写,则子类的资料要先读。