在Android中要使用Intent来传值,如果不是基本类型就必须是实现Serializable或是Parcelable的,其中Serializable是Java通用的,Parcelable却是Android平台特有的,因此在Android中使用这种方式有更好的性能,但是呢实现这个比实现Serializable要麻烦不少。下面记录下实现其所需要的步骤吧
- 让类继承Parcelable接口,并实现两个接口方法,如下,其中describeContents一般可以不管他,在writeToParcel里面向dest写入实体类的成员变量
/** * 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. */ public int describeContents(); /** * 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对象,在这个构造方法里面把类成员变量一个个从Parcel中读取出来,此处读取和刚才的写入顺序应该是对应的。这一步其实是为了下一步调用准备的
- 为这个类加一个静态常量 public static final Creator<T> CREATOR,其中T换成自己的类名,这个常量名字必须是这个,这个常量赋值用new Creator<T>()来构造,要构造这个又要实现两个方法,一个是实例化单个对象的,一个是用来实例化对象数组的,这里实例化单个对象的就直接用第2步的构造方法返回就行,另一个直接new 一个size大小的对象数组就行
如此,最简单的实体类实现Parcelable就完成了,下面贴一个完整的例子,类很简单就两个成员变量及setter()和getter()
public class GroupbuyCategory implements Parcelable {
private long id;
private String name;
public static final Creator<GroupbuyCategory> CREATOR=new Creator<GroupbuyCategory>() {
@Override
public GroupbuyCategory createFromParcel(Parcel source) {
return new GroupbuyCategory(source);
}
@Override
public GroupbuyCategory[] newArray(int size) {
return new GroupbuyCategory[size];
}
};
public GroupbuyCategory(Parcel in){
id=in.readLong();
name=in.readString();
}
public GroupbuyCategory(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(name);
}
}