Android源码学习系列--Parcelable

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

一个典型的实现如下:

public class MyParcelable implements Parcelable { private int mData; public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeInt(mData); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public MyParcelable createFromParcel(Parcel in) { return new MyParcelable(in); } public MyParcelable[] newArray(int size) { return new MyParcelable[size]; } }; private MyParcelable(Parcel in) { mData = in.readInt(); } }

/** * 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)". */ public static final int PARCELABLE_WRITE_RETURN_VALUE = 0x0001; /** * 方法describeContents()使用的掩码。在分组时,每位都被认为是有潜在特殊含义的 */ public static final int CONTENTS_FILE_DESCRIPTOR = 0x0001; /** *对象在Parcelable中特定的编码形式 */ public int describeContents(); /** * 将对象拼合进Parcel中 */ public void writeToParcel(Parcel dest, int flags); /** * 上面提到的CREATOR字段必须实现的接口 */ public interface Creator { /** *创建一个Parcelable对象,并将之前Parcelable.writeToParcel()写入到Parcel中的对象实例化并返回 */ public T createFromParcel(Parcel source); /** * 创建一个Parcelable对象数组 */ public T[] newArray(int size); }

你可能感兴趣的:(移动开发)