关於 Parcelable 实作以及继承

看例子

[java]  view plain  copy
  1. class Shape implements Parcelable {  
  2.   public int left;  
  3.   public int top;  
  4.   public int width;  
  5.   public int height;  
  6.    
  7.   // CREATOR part is omitted  
  8.    
  9.   protected Shape(Parcel in) {  
  10.     readFromParcel(in);  
  11.   }  
  12.    
  13.   public void readFromParcel(Parcel in) {  
  14.     left = in.readInt();  
  15.     top = in.readInt();  
  16.     width = in.readInt();  
  17.     height = in.readInt();  
  18.   }  
  19.    
  20.   @Override  
  21.   public int describeContents() {  
  22.     return 0;  
  23.   }  
  24.    
  25.   @Override  
  26.   public void writeToParcel(Parcel out, int flags) {  
  27.     out.writeInt(left);  
  28.     out.writeInt(top);  
  29.     out.writeInt(width);  
  30.     out.writeInt(height);  
  31.   }  
  32. }  

子类:

[java]  view plain  copy
  1. class RoundedRectangle extends Rectangle {  
  2.   public int radius;  
  3.   // CREATOR part is omitted  
  4.    
  5.   protected RoundedRectangle(Parcel in) {  
  6.     super(in);  
  7.   }  
  8.    
  9.   public void readFromParcel(Parcel in) {  
  10.     super.readFromParcel(in);  
  11.     radius = in.readInt();  
  12.   }  
  13.    
  14.   @Override  
  15.   public void writeToParcel(Parcel out, int flags) {  
  16.     super.writeToParcel(out, flags);  
  17.     out.writeInt(radius);  
  18.   }  
  19. }  

注意事项:

  • 只有父类需要 implements Parcelable
  • 只有父类需要实作 describeContents() 方法
  • 如果子类没有增加其他的成员,则可以不用实作那些parceling 的方法
  • 写入/读出顺序要写正确。如果父类先写,则父类要先读,如果子类先写,则子类的资料要先读。
参考资料来源:http://idlesun.blogspot.co.il/2012/12/android-parcelable-example-3-subclass

你可能感兴趣的:(关於 Parcelable 实作以及继承)