Intent Parcelable 传递ArrayList使用方法

1.定义我的类并实现Parcelable 接口

定义变量

private Long id;
/** Not-null value. */
private String Name;
private long Type;
/** Not-null value. */
private String MatchTimes;
private boolean Shield;
private boolean isSelected;
重构Setter Getter

private Substances(Parcel in) {
    id=in.readLong();
    Name = in.readString();
    Type = in.readLong();
    MatchTimes = in.readString();
    Shield=in.readByte()!=0;
    isSelected = in.readByte() != 0;
}
重写这些方法

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeLong(id);
    dest.writeString(Name);
    dest.writeLong(Type);
    dest.writeString(MatchTimes);
    dest.writeByte((byte) (Shield ? 1 : 0));
    dest.writeByte((byte) (isSelected ? 1 : 0));
}
public static final Creator CREATOR = new Creator() {
    @Override
    public Substances createFromParcel(Parcel in) {
        return new Substances(in);
    }

    @Override
    public Substances[] newArray(int size) {
        return new Substances[size];
    }
};
写完之后看看怎么传递哈

public void editClick(View view) {
    Intent intent = new Intent(this, EditActivity.class);
    Bundle bundle=new Bundle();
    bundle.putParcelableArrayList("sub", (ArrayListextends Parcelable>) this.substancesList);
    intent.putExtra("bundle", bundle);
    startActivity(intent);
}
在看看怎么接收

Bundle bundleObject = getIntent().getParcelableExtra("bundle");
if(bundleObject!=null)
{
    substancesList=bundleObject.getParcelableArrayList("sub");
    Log.i("EditActivity", "substanceList size:"+substancesList.size());
}
就这样吧 哈哈

你可能感兴趣的:(Android,Basic,Technology)