Parcelable使用
来源:互联网 发布:php环境linux 编辑:程序博客网 时间:2024/06/07 01:49
在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); }}
0 0
- Parcelable使用
- Parcelable使用
- Android Parcelable的使用
- Parcelable的使用
- Parcelable接口使用
- Android Parcelable的使用
- Parcelable 基本使用
- Android Parcelable的使用
- Android Parcelable的使用
- Android Parcelable的使用
- Parcelable接口的使用
- Parcelable接口的使用
- Parcelable接口的使用
- Android Parcelable的使用
- Parcelable接口的使用
- Parcelable接口的使用
- Parcelable接口的使用
- Parcelable接口的使用
- iPhone必须掌握的几个日常使用技巧
- 数据结构实验总览及相关代码
- 黑苹果安装及相关注意事项之一,前提
- linux学习(10)权限与命令间的关系
- STM32在程序中禁用JTAG功能后不能进行仿真的解决办法
- Parcelable使用
- svn 1.8 unexpected http status 400 ''
- 启发式算法
- android studio报错Error:Project with path 'XXXX' could not be found解决办法
- 我们可能会遇到的距离量算方法
- 【POJ3974】Palindrome Manacher、模板题 裸题
- VMware11安装Mac OS X10.9.3提示不可恢复错误(vcpu-0) 的解决方法
- stl algorithm清单
- GDAL官网 OGR API Tutorial学习笔记一:Reading From OGR