Parcelable
安卓传递对象,要求对象序列化, 安卓提供2种序列化接口:
- Serializable
- Parcelable
Parcelable 接口来序列化,是Android提供的一个比Serializable 效率更高的序列化类。
实现序列化
Parcelable需要实现三个函数
- void writeToParcel(Parcel dest, int flags)将需要序列化存储的数据写入外部提供的Parcel对象dest。读取Parcel数据的次序要和这里的write次序一致,否则可能会读错数据。
- describeContents()描述,直接返回0即可。
- static final Parcelable.Creator对象CREATOR这个CREATOR命名是固定的,而它对应的接口有两个方法:createFromParcel(Parcel source) 实现从source创建出JavaBean实例的功能。
newArray(int size) 创建一个类型为T,长度为size的数组,仅一句话(return new T[size])即可。估计本方法是供外部类反序列化本类数组使用。
例
public class Chat implements Parcelable{ private int sourceId; private String name,content,time,nameFrom; private int mode,count; public Chat() { // TODO Auto-generated constructor stub } //该静态域是必须要有的,而且名字必须是CREATOR,否则会出错 public static final Creator<Chat> CREATOR = new Creator<Chat>() { @Override public Chat createFromParcel(Parcel source) { //从Parcel读取通过writeToParcel方法写入的Chat的相关成员信息 Chat chat = new Chat(); chat.content = source.readString(); chat.time = source.readString(); chat.nameFrom = source.readString(); chat.mode = source.readInt(); chat.name = source.readString(); //更加读取到的信息,创建返回对象 return chat; } @Override public Chat[] newArray(int size) { // TODO Auto-generated method stub //返回Chat对象数组 return new Chat[size]; } }; @Override public int describeContents() { // TODO Auto-generated method stub return 0; } //实现Parcel接口必须覆盖实现的方法 @Override public void writeToParcel(Parcel dest, int flags) { /*将Chat的成员写入Parcel, * 注:Parcel中的数据是按顺序写入和读取的,即先被写入的就会先被读取出来 */ dest.writeString(this.content); dest.writeString(this.time); dest.writeString(this.nameFrom); dest.writeInt(this.mode); dest.writeString(this.name); } }