android Parcelable類表示該類可以用來序列化,打包爲數據流對象Parcel,通常用於進程間通信傳遞自定義數據類型。
Parcel也相應的提供了一系列write/get方法方便打包和解包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);
在此方法中,需要將當前類需要保存的數據用Parcel.write*方法寫入dest中,打包爲Parcel對象。
同時在當前類中也需要定義一個全局static final常量CREATOR,同時實現其中的解包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);
}
import android.os.Parcel;
import android.os.Parcelable;
public class Book implements Parcelable{
private String name;
private int count;
@Override
public int describeContents() {
return 0;
}
// write all parameters to parcel
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(count);
}
public static final Parcelable.Creator<Book> CREATOR = new Parcelable.Creator<Book>() {
@Override
public Book createFromParcel(Parcel source) {
Book book = new Book();
book.name = source.readString();
book.count = source.readInt();
return book;
}
@Override
public Book[] newArray(int size) {
return new Book[size];
}
};
}
需要注意的是打包/解包時數據應該儘量一致,即wirteToParcel和createFromParcel中讀寫的順序應該一致。