Parcelable数据序列化传递
Parcelable 是 Android 中的一个接口,用于在不同组件之间传递数据。与 Java 中的 Serializable 接口不同,Parcelable 接口更高效,因为它使用了一种基于内存的序列化机制,避免了将对象序列化成字节流的开销。通常情况下,如果需要在不同组件之间传递数据,建议使用 Parcelable 接口来实现。
// 定义一个 Parcelable 类
public class Person implements Parcelable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
protected Person(Parcel in) {
name = in.readString();
age = in.readInt();
}
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];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
// getter 和 setter 方法省略
}
// 在第一个 Activity 中创建 Person 对象并传递给第二个 Activity
Person person = new Person("John", 30);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("person", person);
startActivity(intent);
// 在第二个 Activity 中获取传递过来的 Person 对象
Person person = getIntent().getParcelableExtra("person");