一 传递Serializable对象
1.对象实现Serializable接口
package com.example.myintent.simple03; import java.io.Serializable; // 必须实现Serializable接口,此对象才有传递的资格 public class Student implements Serializable { public int id; public String name; public int age; }
2.传递数据
public void startAction(View view) { Intent intent = new Intent(this, MainActivity2.class); intent.putExtra("name","ljj"); intent.putExtra("sex","M"); startActivity(intent); }
3.获取数据
Intent intent = getIntent(); String name = intent.getStringExtra("name"); char sex = intent.getCharExtra("sex", 'A'); Toast.makeText(this,name+sex,Toast.LENGTH_LONG).show();
二 传递Parcelable对象
1.对象实现Parcelable接口
package com.example.myintent.simple04; import android.os.Parcel; import android.os.Parcelable; // JVM平台 Java开发 Serializable // TODO 推荐的方式 Android 必须使用 Parcelable,因为这个是支持 兼容 安卓虚拟机 比Serializable 性能高很多 // 实现Parcelable接口 public class Student implements Parcelable { // 我们自定义的成员 public String name; public int age; public Student() { } // TODD 注意:读取的顺序 和写入的顺序 必须一致 否则报错 // 构造函数 protected Student(Parcel in) { // 从parcel对象中读取成员 然后赋值 name = in.readString(); age = in.readInt(); } // creator 一定要有 自动生成 不需要自己写 public static final Creator<Student> CREATOR = new Creator<Student>() { // 创建Student对象 并且Parcel构建好 传递给我们的student @Override public Student createFromParcel(Parcel in) { return new Student(in); } @Override public Student[] newArray(int size) { return new Student[size]; } }; // 系统拓展用的 @Override public int describeContents() { return 0; } // 把属性写入到 Parcel对象里面去 @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeInt(age); } }
2.传递数据
public void startAction(View view) { Intent intent = new Intent(this, MainActivity2.class); Student student = new Student(); student.name = "ljj"; student.age = 19; // 传递对象 让intent 携带过去 intent.putExtra("student",student); startActivity(intent); }
3.获取数据
Intent intent = getIntent(); // 这里不需要强转 Student student = intent.getParcelableExtra("student"); Toast.makeText(this,student.name+student.age,Toast.LENGTH_LONG).show();
三 两种方式对比
传递Serializable接口的对象: Serializable 是面向JVM java虚拟机的
传递Parcelable接口的对象:Parcelable是面向Android虚拟机的,比Serializable 性能高很多,推荐 Android开发必须用这个,因为和Android虚拟机兼容