使用Bundle 或者Intent传递自定义对象,需要把自定义对象序列化。
序列化表示将一个对象转换成可存储或可传输的状态。序列化后的对象可以在网络上传输,也可以存储到本地。序列化的方法有两种:Serializable方式和Parcelable方式。
1.Serializable方式
Serializable即序列化的意思,如果有个自定义类是Person.java,里面有name和age两个字段
想要序列化可以这样写:
public class Person implements Serializable {
private String name;
private int age;
public String getName(){
return name;
}
public int getAge(){
return age;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
}
set,get方法都是实体类生成赋值和读取数据用的,重点就是第一行 implements Serializable表示Person类实现了Serializable接口,则所有的Person对象都是可以序列化的了
传递数据时:
Intent:
//发送数据端
Person person =new Person();
person.setName("Tom");
person.setAge(20);
Intent intent = new Intent(this,NewActivity.class);//或初始化其他Intent的构造函数
intent.putExtra("key",person);//key是你定义的键值对的键值,唯一即可。
context.startActivity(intent);
//接收数据端,比如一个Activity:
Person person =(Person)getIntent().getSerializableExtra("key")
Bundle:
//发送数据端
Person person =new Person();
person.setName("Tom");
person.setAge(20);
Bundle bundle = new Bundle();
bundle.putSerializable("key",person);//key是你定义的键值对的键值,唯一即可。
//接收数据端
Person person =(Person)bundle.getSerializable("key");
Serializable方式比较简单,但由于会把整个对象进行序列化,效率会比Parcelable方式低。
2.Parcelable方式
Parcelable方式序列化效率更高,不过代码量会多一点儿。
举个复杂一点的例子
public class MainFunctionBean implements Parcelable { //实现Parcelable 接口
private String title;
private int bitmapResKey;
private boolean isLongPressed = false;
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setBitmapResKey(int bitmapResKey) {
this.bitmapResKey = bitmapResKey;
}
public int getBitmapResKey() {
return bitmapResKey;
}
public boolean isLongPressed() {
return isLongPressed;
}
public void setLongPressed(boolean longPressed) {
isLongPressed = longPressed;
}
@Override
public int describeContents() { //默认覆写的方法,不用改
return 0;
}
public static final Parcelable.Creator<MainFunctionBean> CREATOR = new Parcelable.Creator<MainFunctionBean>() {
@Override
public MainFunctionBean createFromParcel(Parcel source) {
//重点覆写 的方法,各个字段的声明顺序必须和 writeToParcel方法里的一致
MainFunctionBean mainFunctionBean = new MainFunctionBean();
mainFunctionBean.title = source.readString();
mainFunctionBean.bitmapResKey = source.readInt();
mainFunctionBean.isLongPressed = source.readByte() != 0;//序列化的数据恢复成boolean类型
return mainFunctionBean;
}
@Override
public MainFunctionBean[] newArray(int size) { //默认覆写的方法,把size传进数组
return new MainFunctionBean[size];
}
};
@Override
public void writeToParcel(Parcel dest, int flags) { //重点覆写 的方法,需要将本实体类的字段一 一写出进行序列化。
dest.writeString(title);//title是String类型
dest.writeInt(bitmapResKey);//bitmapResKey是int类型
dest.writeByte((byte) (isLongPressed ? 1 : 0));//isLongPressed 是boolean类型,改写成Byte便于序列化
}
}
传递数据时,方法和Serializable差不多只是Serializable这个词对应变成了Parcelable