目录
一 传递Serializable对象
1 对象实现Serializable接口
package com.example.myintent;
import java.io.Serializable;
//必须实现Serializable接口,才有传递的资格,将对象序列化了才能传输
public class Student implements Serializable {
public String name;
public int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
2 传递数据
//跳转到activity6
public void jump(View view) {
Intent intent = new Intent(this, MainActivity6.class);
//该对象实现Serializable接口,序列化了才能传输
Student student = new Student("future",3);
intent.putExtra("student",student);
startActivity(intent);
}
3 获取数据
//获取数据
Intent intent = getIntent();
Student student = (Student)intent.getSerializableExtra("student");
Toast.makeText(this, student.name+":"+student.age, Toast.LENGTH_SHORT).show();
*二 传递Parcelable对象(推荐)
1 对象实现Parcelable接口
写成员变量,alt+enter实现方法
package com.example.myintent;
import android.os.Parcel;
import android.os.Parcelable;
//Android开发必须用这个,因为和Android虚拟机兼容,比Serializable性能高很多 → 推荐的方式
//此对象实现Parcelable接口,就具备传递的资格
public class Person implements Parcelable {
//我们自己定义的成员
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//构造函数
//从Parcel里读取数据,赋值给成员变量
protected Person(Parcel in) {
name = in.readString();
age = in.readInt();
}
//TODO 注意读取的顺序和写入的顺序必须一致,否则会报错
//先写数据后读数据
//把属性写入Parcel对象中
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
//现在用不到,可能是以后Parcelable的扩展操作,不用管
@Override
public int describeContents() {
return 0;
}
//Creator一定要有,自动生成的
public static final Creator<Person> CREATOR = new Creator<Person>() {
//创建对象
@Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}
2 传递数据
//跳转到activity8
public void jump(View view) {
Intent intent = new Intent(this, MainActivity8.class);
Person p = new Person("blue",14);
intent.putExtra("person",p);
startActivity(intent);
}
3 获取数据
Intent intent = getIntent();
//返回值是泛型,不需要类型转换
Person person = intent.getParcelableExtra("person");
Toast.makeText(this, person.name+":"+person.age, Toast.LENGTH_SHORT).show();
效果
三 两种方式的比较
传递Serializable接口的对象: Serializable 是面向JVM java虚拟机的
传递Parcelable接口的对象:Parcelable是面向Android虚拟机的,性能更高,推荐
Android开发必须用这个,因为和Android虚拟机兼容