Android Bundle传递数据

春衣少年当酒歌,起舞四顾以笑和。这篇文章主要讲述Android Bundle传递数据相关的知识,希望能为你提供帮助。
1.传递普通数据

Intent intent=new Intent(MainActivity.this,TwoActivity.class); Bundle bundle=new Bundle(); bundle.putString("name","张三"); bundle.putInt("age",18); bundle.putString("gender","男"); intent.putExtras(bundle); startActivity(intent);

获取传递的数据
Bundle bundle=getIntent().getExtras(); String name=bundle.getString("name"); String gender=bundle.getString("gender"); int age =bundle.getInt("age");

 
2.传递Serializable数据1.创建一个类实现Serializable
【Android Bundle传递数据】2.传递数据
Intent intent=new Intent(MainActivity.this,TwoActivity.class); Bundle bundle=new Bundle(); Person1 p1=new Person1("张三","男",18); bundle.putSerializable("person",p1); intent.putExtras(bundle); startActivity(intent);

 
3.接受数据
Bundle bundle=getIntent().getExtras(); Person1 p1= (Person1) bundle.getSerializable("person"); String name=p1.getName(); String gender=p1.getGender(); int age =p1.getAge();

 
 
 
3.传递Parcelable数据1.创建类实现Parcelabel
public class Person3 implements Parcelable { private String name; private String gender; private int age; public Person3(String name, String gender, int age) { this.name = name; this.gender = gender; this.age = age; }public String getName() { return name; }public String getGender() { return gender; }public int getAge() { return age; }@Override public String toString() { return "Person3{" + "name=‘" + name + ‘\‘‘ + ", gender=‘" + gender + ‘\‘‘ + ", age=" + age + ‘}‘; }public static final Parcelable.Creator< Person3> CREATOR=new Parcelable.Creator< Person3> (){/** * 供外部类反序列话本类数组使用 * @param source * @return */@Override public Person3 createFromParcel(Parcel source) { return new Person3(source); }/** * 从Parcel中读取数据 * @param size * @return */ @Override public Person3[] newArray(int size) { return new Person3[size]; } }; /** * 默认返回0就行 * @return */ @Override public int describeContents() { return 0; }/** * 把值写进Parcel中 * @param dest * @param flags */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeString(gender); dest.writeInt(age); }/** * 这里的读取数据必须与writeToParacel(Parcel dest,int flags)一致,否则就会出错 * @param source */ public Person3(Parcel source) { name = source.readString(); gender=source.readString(); age = source.readInt(); } }

 
2.传递数据
Intent intent=new Intent(MainActivity.this,TwoActivity.class); Bundle bundle=new Bundle(); Person3 p3=new Person3("张三","男",18); bundle.putParcelable("person",p3); intent.putExtras(bundle); startActivity(intent);

 
3.接受数据
Bundle bundle=getIntent().getExtras(); Person3 p3= bundle.getParcelable("person"); String name=p3.getName(); String gender=p3.getGender(); int age =p3.getAge();

 

    推荐阅读