介绍
Bundle,是Android开发中的一个类,用于Activity之间传输数据用。
传递基本数据类型
1. 发送数据
//使用Bundle封装基本数据类型
Bundle bundle = new Bundle();
bundle.putString("name","alin");
bundle.putInt("age",22);
//创建Intent并将Bundle装入
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("bundle",bundle);
//发送
startActivity(intent);
2. 接收数据
//获取Bundle
Bundle bundle = getIntent().getBundleExtra("bundle") ;
//获取name
String name = bundle.getString("name") ;
//获取age
int age = bundle.getInt("age") ;
传递对象
1. 对象实现序列化接口
public class Person implements Serializable {
private String name;
private int age;
private static final long serialVersionUID = 1L;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2. 发送数据
//设置对象值
Person person = new Person();
person.setName("alin");
person.setAge(22);
//将person装入Bundle
Bundle bundle = new Bundle();
bundle.putSerializable("person",person);
//创建Intent并将Bundle装入
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("bundle",bundle);
//发送
startActivity(intent);
3. 接收数据
//获取Bundle
Bundle bundle = getIntent().getBundleExtra("bundle") ;
//获取Person对象
Person person = (Person) bundle.getSerializable("person");
//获取name属性
String name = person.getName();
//获取age属性
int age = person.getAge() ;
END