1. 实现Serializable接口 比较简单直接实现即可
public class Student implements Serializable{ private static final long serialVersionUID = 1L; public int id; public String name; }
class Teacher implements Parcelable{ private int id; private String name; public Teacher(int id, String name) { this.id = id; this.name = name; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeString(name); } public static final Parcelable.Creator<Teacher> CREATOR = new Parcelable.Creator<Teacher>() { @Override public Teacher createFromParcel(Parcel source) { Teacher teacher = new Teacher(source.readInt(), source.readString()); return teacher; } @Override public Teacher[] newArray(int size) { return null; } }; }
// Serializable序列化传送 ArrayList<Student> list = new ArrayList<Student>(); Student student = new Student(1, "Jim"); list.add(student); Intent intent = new Intent(this, SecondActivity.class); intent.putExtra("STUDENT_INFO", list); startActivity(intent);
// parcel序列化传送 ArrayList<Teacher> list = new ArrayList<Teacher>(); Teacher teacher1 = new Teacher(1, "techaer1"); list.add(teacher1); Intent intent = new Intent(this, SecondActivity.class); intent.putExtra("TEACHER_INFO", list); startActivity(intent);
Intent intent = getIntent(); // serializable ArrayList<Student> list = (ArrayList<Student>) intent.getSerializableExtra("STUDENT_INFO");
// parcelble ArrayList<Teacher> list = intent.getParcelableArrayListExtra("TEACHER_INFO");