在Android的Intent中传递实体的时候,需要对对象进行序列化,然后通过Bundle的putSerializable()、getSerializable()或者putParcelable()、getParcelable()方法实体存储和取出,方便我们在两个不同Activity之间传递实体,下面分别进行介绍:
1、创建实体Computer,使用Serializable序列化
public class Computer implements Serializable {
private static final long serialVersionUID = -7060210544600464481L;
private String name;
private String color;
private float price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
2、创建实体Phone,实现Parcelable进行序列化,如下:
public class Phone implements Parcelable {
private String phoneName;// 定义手机的品牌
private float phonePrice;// 手机的价格
private float sdkVersion;// 手机系统版本
public String getName() {
return phoneName;
}
public void setName(String name) {
this.phoneName = name;
}
public float getPrice() {
return phonePrice;
}
public void setPrice(float price) {
this.phonePrice = price;
}
public float getSdkVersion() {
return sdkVersion;
}
public void setSdkVersion(float sdkVersion) {
this.sdkVersion = sdkVersion;
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(phoneName);
dest.writeFloat(phonePrice);
dest.writeFloat(sdkVersion);
}
public static final Parcelable.Creator<Phone> CREATOR = new Creator<Phone>() {
@Override
public Phone createFromParcel(Parcel source) {
Phone phone=new Phone();
phone.phoneName=source.readString();
phone.phonePrice=source.readFloat();
phone.sdkVersion=source.readFloat();
return phone;
}
@Override
public Phone[] newArray(int size) {
// TODO Auto-generated method stub
return new Phone[size];
}
};
}
3、将序列化后的对象通过Intent传递,创建MainActivity和NextActivity,如下
你可能感兴趣的文章
转载请注明出处: https://www.teachcourse.cn/350.html ,谢谢支持!