Intent意圖不僅可以傳遞基本數據類型的數據,也可以傳遞對象數據。
android提供了兩種傳遞對象的方式:對象數據的序列化和對象數據的分解。
一、數據的序列化
使將要傳遞的對象類實現Seriazliable接口。
/*1.使將要傳遞的對象實現Serializable接口,實現序列化*/
public class Person implements Serializable {
private int age;
private String name;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
}
/*2.發送對象數據*/
Intent intent = new Intent(this,SecondActivity.class);
Person p = new Person();
p.setAge(12);
p.setName("zyj");
intent.putExtra("person",p);
/*3.得到Intent對象並獲取序列化數據*/
Intent intent = getIntent();
Person person = (Person)intent.getSerializableExtra("person");
int age = person.getAge();
String name = person.getName();
二、數據對象的分解
/*1.使將要傳遞的類實現Parceable接口併爲其成員變量提供相應的get和set方法*/
public class Person implements Parcelable {
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
//複寫describeContents()方法,返回0
@Override
public int describeContents() {
return 0;
}
//複寫writerToParcel方法,將對象的成員變量數據使用Parcel對象輸出
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
//創建變量CREATOR,格式爲固定格式,泛型的類型就是我們要發送的對象數據的類名。
public static final Creator<Person> CREATOR = new Creator<Person>(){
//上文中用Parcel對象寫入,現在用Parecl對象讀取。注意本處讀的順序必須和上面寫的順序一致
@Override
public Person createFromParcel(Parcel source) {
Person person = new Person();
person.name = source.readString();
person.age = source.readInt();
return person;
}
//複寫newArray方法,格式如下
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}
//2.發送對象
//設置數據對象
Person person = new Person();
person.setName("zyj");
person.setAge(23);
//設置意圖併發送數據
Intent intent = new Intent(this,SecondActivity.class);
intent.putExtra("person",person);
startActivity(intent);
/*3.獲取到發送的對象數據*/
Intent intent = getIntent();
Person person = (Person) intent.getParcelableExtra("person");
String name = person.getName();
int age = person.getAge();
上面兩種方式操作不同,若無特殊要求,建議使用Parcel方式實現對象的傳遞,雖然書寫麻煩但是性能好。Serializable接口爲android重量級組件,較爲耗費性能。