在Android中,使用Intent传递数据有多种方法。以下是一些常见的方法:
putExtra()方法传递基本数据类型:Intent intent = new Intent(FirstActivity.this, SecondActivity.class); intent.putExtra("key1", "value1"); // 传递字符串类型数据 intent.putExtra("key2", 123); // 传递整数类型数据 intent.putExtra("key3", 3.14f); // 传递浮点数类型数据 intent.putExtra("key4", true); // 传递布尔类型数据 putExtra()方法传递对象类型数据:首先,需要确保要传递的对象实现了Serializable接口。例如,如果你要传递一个Person对象,可以这样做:
public class Person implements Serializable { private String name; private int age; // 构造方法、getter和setter方法 } Intent intent = new Intent(FirstActivity.this, SecondActivity.class); Person person = new Person("John", 25); intent.putExtra("key5", person); // 传递Person对象 Bundle传递数据:Bundle对象可以用来存储多个键值对,然后将其作为额外的数据附加到Intent中。
Intent intent = new Intent(FirstActivity.this, SecondActivity.class); Bundle bundle = new Bundle(); bundle.putString("key1", "value1"); bundle.putInt("key2", 123); bundle.putFloat("key3", 3.14f); bundle.putBoolean("key4", true); intent.putExtras(bundle); // 将Bundle附加到Intent 在接收数据的Activity中,可以使用getExtras()方法获取Bundle对象,然后使用相应的get()方法获取数据。
Intent intent = getIntent(); Bundle bundle = intent.getExtras(); String value1 = bundle.getString("key1"); int value2 = bundle.getInt("key2"); float value3 = bundle.getFloat("key3"); boolean value4 = bundle.getBoolean("key4"); 注意:使用Bundle传递对象时,对象需要实现Parcelable接口,而不是Serializable接口。