Android Bundle总结
版本
修改内容
日期
修改人
1.0
初稿
2013/03/06
skywang
1 Bundle介绍
Bundle主要用于传递数据;它保存的数据,是以key-value(键值对)的形式存在的。
我们经常使用Bundle在Activity之间传递数据,传递的数据可以是boolean、byte、int、long、float、double、string等基本类型或它们对应的数组,也可以是对象或对象数组。当Bundle传递的是对象或对象数组时,必须实现Serializable或Parcelable接口。下面分别介绍Activity之间如何传递基本类型、传递对象。
2传递基本类型
Bundle提供了各种常用类型的putXxx()/getXxx()方法,用于读写基本类型的数据。Bundle操作基本数据类型的API表格如下所示:
写数据的方法如下:
// "com.test" is the package name of the destination class
// "com.test.Activity02" is the full class path of the destination class
Intent intent = new Intent().setClassName("com.bundletest", "com.bundletest.Bundle02");
Bundle bundle = new Bundle();
bundle.putString("name", "skywang");
bundle.putInt("height", 175);
intent.putExtras(bundle);
startActivity(intent);
// end current class
finish();
对应的读数据的方法如下:
Bundle bundle = this.getIntent().getExtras();
String name = bundle.getString("name");
int height = bundle.getInt("height");
3传递Parcelable类型的对象
3.1 Parcelable说明
Parcelable是Android自定义的一个接口,它包括了将数据写入Parcel和从Parcel中读出的API。一个实体(用类来表示),如果需要封装到bundle消息中去,可以通过实现Parcelable接口来实现。
Parcelable和Serializable的API如下表:
3.2 Parcelable接口说明
public interface Parcelable {
//内容描述接口,基本不用管
public int describeContents();
//写入接口函数,打包
public void writeToParcel(Parcel dest, int flags);
//读取接口,目的是要从Parcel中构造一个实现了Parcelable的类的实例处理。因为实现类在这里还是不可知的,所以需要用到模板的方式,继承类名通过模板参数传入。
//为了能够实现模板参数的传入,这里定义Creator嵌入接口,内含两个接口函数分别返回单个和多个继承类实例。
public interface Creator {
public T createFromParcel(Parcel source);
public T[] newArray(int size);
}
}
3.3 Parcelable接口的实现方法
从parcelable接口定义中,我们可以看到,实现parcelable接口,需要我们实现下面几个方法:
(01)describeContents方法。内容接口描述,默认返回0就可以;
(02)writeToParcel 方法。该方法将类的数据写入外部提供的Parcel中.即打包需要传递的数据到Parcel容器保存,以便从parcel容器获取数据,该方法声明如下:
writeToParcel(Parcel dest, int flags) 具体参数含义见doc文档
(3.)静态的Parcelable.Creator接口,本接口有两个方法:
createFromParcel(Parcelin) 从Parcel容器中读取传递数据值,封装成Parcelable对象返回逻辑层。
newArray(int size) 创建一个类型为T,长度为size的数组,仅一句话(returnnew T[size])即可。方法是供外部类反序列化本类数组使用。
4传递Serializable类型的对象
4.1 Serializable说明
Serializable是一个对象序列化的接口。一个类只有实现了Serializable接口,它的对