当在一个 Activity 中启动另一个 Activity 时,经常需要传递一些数据。这时就可以通过 Intent来实现,因为 Intent 通常被称为是两个 Activity 之间的信使,通过将要传递的数据保存在 Intent 中,就可以将其传递到另一个 Activity 中了。在 Android 中,可以将要保存的数据存放在 Bundle 对象中,然后通过 Intent 提供的 putExtras() 方法将要携带的数据保存到 Intent 中。通过 Intent 传递数据的示意图如图
Bundle是一个key-value(键-值)对的组合,用于保存要携带的数据包。这些数据可以是boolean、byte、int、long、float、double和String等基本类型或者对应的数组,也可以是对象或者对象数组。如果是对象或者对象数组时,必须实现Serializable或者Parcelable接口。
//传递的数据
Bundle bundle = new Bundle();
bundle.putString("msg", "传递我这个消息");
Message message = Message.obtain();
message.setData(bundle); //message.obj=bundle 传值也行
//获取输入的用户信息
String name = ((EditText) findViewById(R.id.et_name)).getText().toString();
Intent intent = new Intent(MainActivity.this, AddressActivity.class);
Bundle bundle = new Bundle();
bundle.putCharSequence(“name”, name); //保存姓名
intent.putExtras(bundle); //将Bundle对象添加到Intent对象中
Intent intent = getIntent(); //获取Intent对象
Bundle bundle = intent.getExtras();
//获取显示姓名的TextView组件
TextView name = (TextView) findViewById(R.id.name);
//获取输入的姓名并显示到TextView组件中
name.setText(bundle.getString(“name”));