标签:
序列化主要是用来传递类的信息,一般java有提供serializable类,这个类用的较多,不过在android上面似乎效率不高,于是google开发了针对性的优化的接口,parcelable接口。
从名字上来看,parcel是包裹的意思,传递用包裹来表示,比较形象。不过这个接口以及文档,写的比较抽象,stackoverflow上面的人说肯定是C++程序员写的、、、所以广大Java程序员需要耐着性子看。
首先,我们需要实现接口Parcelable。
然后,有几个方法需要重写,
describeContents()这个按照默认,我们通常返回0,据文档上面说是FileDescriptor,没有搞太懂。
Describe the kinds of special objects contained in this Parcelable‘s * marshalled representation. * * @return a bitmask indicating the set of special object types marshalled * by the Parcelable.
writeToParcel(Parcel dest,int flags) ,把这个对象放进Parcel中。第一个参数是应该被写入的parcel,第二个参数一般我们不怎么用。
/** * Flatten this object in to a Parcel. * * @param dest The Parcel in which the object should be written. * @param flags Additional flags about how the object should be written. * May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}. */ public void writeToParcel(Parcel dest, int flags);
另外需要注意一个Creator,只有实现了这个接口,parcel常量类才可以将其parcelable。
这个接口有两个方法要重写,
createFromParcel,这个用来创建一个parcel对象的实例。
/** * Interface that must be implemented and provided as a public CREATOR * field that generates instances of your Parcelable class from a Parcel. */ public interface Creator<T> { /** * Create a new instance of the Parcelable class, instantiating it * from the given Parcel whose data had previously been written by * {@link Parcelable#writeToParcel Parcelable.writeToParcel()}. * * @param source The Parcel to read the object‘s data from. * @return Returns a new instance of the Parcelable class. */ public T createFromParcel(Parcel source); /** * Create a new array of the Parcelable class. * * @param size Size of the array. * @return Returns an array of the Parcelable class, with every entry * initialized to null. */ public T[] newArray(int size); }
下面这个是Google提供的官方doc。
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<MyParcelable> CREATOR * = new Parcelable.Creator<MyParcelable>() { * 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(); * }
标签:
原文地址:http://www.cnblogs.com/likeshu/p/5131291.html