第一个Activity中的button定义点击事件:
btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { List<Book> bookList = new ArrayList<Book>(); bookList.add(new Book("yuwen", 100)); bookList.add(new Book("shuxue", 65)); bookList.add(new Book("yingyu", 230)); Family f = new Family("Beijin", 110); Student s = new Student("yq", 25, f, bookList); Intent intent = new Intent(MainActivity.this, SecondActivity.class); intent.putExtra(tag, s); startActivity(intent); } });
第二个Activity中接收:
Intent i = getIntent(); Student s = i.getParcelableExtra(MainActivity.tag);
Student类是主要传递对象,如下:
public class Student implements Parcelable { private String name; private int age; private Family family; private List<Book> bookList; public Student (String name, int age, Family family, List<Book> bookList) { this.name = name; this.age = age; this.family = family; this.bookList = bookList; } protected Student (Parcel in) { name = in.readString(); age = in.readInt(); family = in.readParcelable(Family.class.getClassLoader()); bookList = in.readArrayList(Book.class.getClassLoader()); } @Override public int describeContents () { return 0; } @Override public void writeToParcel (Parcel dest, int flags) { dest.writeString(name); dest.writeInt(age); dest.writeParcelable(family, flags); dest.writeList(bookList); } public static final Creator<Student> CREATOR = new Creator<Student>() { @Override public Student createFromParcel (Parcel in) { return new Student(in); } @Override public Student[] newArray (int size) { return new Student[size]; } }; @Override public String toString () { return "name:" + name + "; age:" + age + "; family addr: " + family.addr + ", famly phone: " + family.phone; } } class Family implements Parcelable { public String addr; public long phone; public Family (String addr, long phone) { this.addr = addr; this.phone = phone; } protected Family (Parcel in) { addr = in.readString(); phone = in.readLong(); } public static final Creator<Family> CREATOR = new Creator<Family>() { @Override public Family createFromParcel (Parcel in) { return new Family(in); } @Override public Family[] newArray (int size) { return new Family[size]; } }; @Override public int describeContents () { return 0; } @Override public void writeToParcel (Parcel dest, int flags) { dest.writeString(addr); dest.writeLong(phone); } } class Book implements Parcelable { public String name; public int page; public Book (String name, int page) { this.name = name; this.page = page; } protected Book (Parcel in) { name = in.readString(); page = in.readInt(); } public static final Creator<Book> CREATOR = new Creator<Book>() { @Override public Book createFromParcel (Parcel in) { return new Book(in); } @Override public Book[] newArray (int size) { return new Book[size]; } }; @Override public int describeContents () { return 0; } @Override public void writeToParcel (Parcel dest, int flags) { dest.writeString(name); dest.writeInt(page); } }
其中Family和Book类都必须实现Parcelable