标签:
使用Intent传递对象数据时,可以使用Intent.putSerializable(Key,Object)和Intent.putParcelable(Key, Object)两种方法,而要传递的对象类型必须实现Serializable接口或者Parcelable接口。下面给出两种实现方式。
实现Serializable接口方式:
public class Person implements Serializable { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return name; } }MainActivity中onCreate方法中 传递数据代码:
Intent intent = new Intent(this, OtherActivity.class); Bundle bundle = new Bundle(); Person p = new Person(); p.setName("baidu"); bundle.putSerializable("person", p); intent.putExtras(bundle); startActivity(intent);
在OtherActivity中取出数据:
Person p = (Person) intent.getSerializableExtra("person");
实现Parcelable接口方式:
public class Person implements Parcelable { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return name; } public static final Parcelable.Creator<Person> CREATOR = new Creator<Person>() { public Person createFromParcel(Parcel source) { Person p = new Person(); p.name = source.readString(); return p; } public Person[] newArray(int size) { return new Person[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); } }MainActivity中onCreate方法中 传递数据代码:
Intent intent = new Intent(this, OtherActivity.class); Bundle bundle = new Bundle(); Person p = new Person(); p.setName("baidu"); bundle.putParcelable("person", p); intent.putExtras(bundle); startActivity(intent);
Person p = intent.getParcelableExtra("person");
http://blog.csdn.net/loongggdroid/article/details/17887975
标签:
原文地址:http://blog.csdn.net/worst_hacker/article/details/45221473