关于Parcelable的数据序列化传递
public class Goods implements Parcelable{ private String name = "";//名称 private float price = 0.0f;//价格 private String describe = "";//描述 private float count = 0.0f;//数量 private float total = 0.0f;//总计 private String unit = "";//单位 private float discount = 0.0f;//折扣
//请无视get set method public float getDiscount() { return discount; } public void setDiscount(float discount) { this.discount = discount; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getDescribe() { return describe; } public void setDescribe(String describe) { this.describe = describe; } public float getCount() { return count; } public void setCount(float count) { this.count = count; } public float getTotal() { return total; } public void setTotal(float total) { this.total = total; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } //以下开始才是重要的 @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int arg1) { //序列化对象,必须按照声明顺序 parcel.writeString(getName()); parcel.writeFloat(getPrice()); parcel.writeString(getDescribe()); parcel.writeFloat(getCount()); parcel.writeFloat(getTotal()); parcel.writeString(getUnit()); parcel.writeFloat(getDiscount()); } public static final Parcelable.Creator<Goods> CREATOR = new Creator<Goods>(){ @Override public Goods createFromParcel(Parcel source) { //必须按照声明顺序 Goods goods = new Goods(); goods.name = source.readString(); goods.price = source.readFloat(); goods.describe = source.readString(); goods.count = source.readFloat(); goods.total = source.readFloat(); goods.unit = source.readString(); goods.discount = source.readFloat(); return goods; } @Override public Goods[] newArray(int size) { return new Goods[size]; } }; }
将数据传入Intent的代码
Intent intent = new Intent(XXXActivity,YYYActivity);
Bundle bundle = new Bundle(); bundle.putParcelableArrayList(KEY, (ArrayList<? extends Parcelable>) goodslist);
intent.putExtras(bundle);
将数据取出
List<Goods> list = intent.getExtras().getParcelableArrayList(KEY);
总之很简单,但是也比较容易忘记,遂记の