Android源码学习系列--Parcelable


实现了该接口的类可以被写入保存在Parcel中。如果实现该接口需要有一个实现了ParcelCreator接口的静态字段CREATOR

一个典型的实现如下:

  1. public class MyParcelable implements Parcelable {  
  2.     private int mData;  
  3.   
  4.     public int describeContents() {  
  5.         return 0;  
  6.     }  
  7.   
  8.     public void writeToParcel(Parcel out, int flags) {  
  9.         out.writeInt(mData);  
  10.     }  
  11.   
  12.     public static final Parcelable.Creator<MyParcelable> CREATOR  
  13.             = new Parcelable.Creator<MyParcelable>() {  
  14.         public MyParcelable createFromParcel(Parcel in) {  
  15.             return new MyParcelable(in);  
  16.         }  
  17.   
  18.         public MyParcelable[] newArray(int size) {  
  19.             return new MyParcelable[size];  
  20.         }  
  21.     };  
  22.       
  23.     private MyParcelable(Parcel in) {  
  24.         mData = in.readInt();  
  25.     }  
  26. }  

 

  1. /** 
  2.      * Flag for use with writeToParcel(Parcel, int): the object being written is a return value, that is the result of a function such as "Parcelable someFunction()", "void        *someFunction(out Parcelable)", or "void someFunction(inout Parcelable)". 
  3.     */  
  4.    public static final int PARCELABLE_WRITE_RETURN_VALUE = 0x0001;  
  5.      
  6.    /** 
  7.     * 方法describeContents()使用的掩码。在分组时,每位都被认为是有潜在特殊含义的 
  8.     */  
  9.    public static final int CONTENTS_FILE_DESCRIPTOR = 0x0001;  
  10.      
  11.    /** 
  12.     *对象在Parcelable中特定的编码形式 
  13.     */  
  14.    public int describeContents();  
  15.      
  16.    /** 
  17.     * 将对象拼合进Parcel中 
  18.     */  
  19.    public void writeToParcel(Parcel dest, int flags);  
  20.   
  21.   
  22.    /** 
  23.     * 上面提到的CREATOR字段必须实现的接口 
  24.     */  
  25.    public interface Creator<T> {  
  26.        /** 
  27.         *创建一个Parcelable对象,并将之前Parcelable.writeToParcel()写入到Parcel中的对象实例化并返回 
  28.         */  
  29.        public T createFromParcel(Parcel source);  
  30.          
  31.        /** 
  32.         * 创建一个Parcelable对象数组 
  33.         */  
  34.        public T[] newArray(int size);  
  35.    }  

相关内容