有些项目中会在两个activity中传输数据,然后根据传输的数据来显示或做其他处理。
比如在第一个activity 有多个按键,每个按键代表的不同的类型,这些按键启动的是同一个activity界面(复用同一个activity),在打开新的activity的时候需要显示不同的标题。
因为每个按键下发送了不同的类型,所以在新的activity中需要对发送过来的数据进行筛选并获取对应的值来显示。
//发送端
//新建方法,把相同的代码封装起来,避免出现重复的代码
private Intent setInformain(Context context, Class<?> cls, String key, String data) {
Intent intent = new Intent(context, cls);
Bundle bundle = new Bundle(); //创建bundle 实例,绑定需要传输的数据
bundle.putString(key, data); //传送两个数据
intent.putExtras(bundle); //把bundle绑定到intent上
return intent;
}
Button1:
startActivity(setInformain(MainActivity.this, PreviewActivity.class, "name", "tom"));
button2:
startActivity(setInformain(MainActivity.this, PreviewActivity.class, "age", "18"));
//接收端
if (null != this.getIntent() && null != this.getIntent().getExtras()) {
//接收到传送过来的Bundle 数据
Bundle getBundle = this.getIntent().getExtras();
//获取bundle中所有key的值
Set<String> getKey = getBundle.keySet();
for (String key : getKey) {
if ("name".equals(key)) {
String name = bundle.getString("name"); //获取值为 tom
} else if ("age".equals(key)) {
String age = bundle.getInt("age"); //获取值为 18
}
}
}