Android中Intent中如何传递对象,一种是 Bundle.putSerializable(Key,Object);另一种是Bundle.putParcelable(Key, Object);当然这些Object是有一定的条件的,前者是实现了Serializable接口,而后者是实现了Parcelable接口

 

1.Serializable

对象类:

public class User implements Serializable{

    public User(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int age;
    public String name;
}

传递类:

Bundle bundle = new Bundle();

bundle.putSerializable("user", new User(26, "xiaohong"));

Intent intent = new Intent(this, DemoActicity.class);

intent.putExtras(bundle);

startActivity(intent);

接受类:

User user = (User)getIntent().getExtras().getSerializable("user");

 

 

Parcelable

对象类:

public class Student implements Parcelable{

    public int number;
    public String name;

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeInt(number);
        parcel.writeString(name);
    }

    /**
     * 1.此处必须加上 public static final
     * 2.此处变量名字必须为  CREATOR
     */
    public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
        @Override
        public Student createFromParcel(Parcel parcel) {
            Student student = new Student();
            student.number = parcel.readInt();
            student.name = parcel.readString();
            return student;
        }

        @Override
        public Student[] newArray(int i) {
            return null;
        }
    };
}

传递类:

Student student = new Student();

student.number = 1;

student.name = "xiaohong";

Bundle bundle = new Bundle();

bundle.putParcelable("student", student);

Intent intent = new Intent(this, DemoActicity.class);

intent.putExtras(bundle);

startActivity(intent);

接受类:

User user = (User)getIntent().getExtras().getParcelable("user");

posted on 2013-03-05 16:23  Snow〃冰激凌  阅读(719)  评论(0编辑  收藏  举报