android Parcelable类

来源:互联网 发布:安卓 java webservice 编辑:程序博客网 时间:2024/05/22 14:51

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);    }


如下为实现了Parcelable接口的Book类,其中有两个基本类型的变量,在进程间传递数据时我们希望可以传递这些信息,则可以将这些变量都写入Parcel对象中。代码如下:

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中读写的顺序应该一致。

0 0
原创粉丝点击