import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable {
private String name = null;
private String city = null;
private int age = 0;
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(name);
dest.writeString(city);
dest.writeInt(age);
}
public static final Parcelable.Creator<Person> CREATOR = new Creator<Person>() {
@Override
public Person createFromParcel(Parcel source) {
// TODO Auto-generated method stub
Person p = new Person();
//赋值次序依照writeToParcel
p.name = source.readString();//----line1
p.city = source.readString();//----line2
p.age = source.readInt(); //----line3
return p;
}
@Override
public Person[] newArray(int size) {
// TODO Auto-generated method stub
return new Person[size];
}
};
}
在createFromParcel方法中对新建对象p属性复制的时候,次序要依照writeToParcel方法中写入的次序,如果将line2和line1交换位置,在读取时得到的Person对象的name和city属性值将发生交换;如果将line3和line1交换位置,在读取时得到的Person对象的name和age属性值将错误
Android中使用Parcelable传递对象,createFromParcel中对象的赋值次序
最新推荐文章于 2024-04-27 15:04:25 发布