在 Android 中,Intent 不仅可以传递基本数据类型(如字符串、整数等),还可以传递复杂的数据结构,包括对象、数组等。以下是一些关于传递复杂数据的示例:

1. 传递对象:
   - 通过 Intent 传递自定义对象,确保该对象实现了 Serializable 或 Parcelable 接口。
// 在发送端
MyObject myObject = new MyObject("John", 25);
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("myObject", myObject);
startActivity(intent);

// 在接收端
Intent receivedIntent = getIntent();
MyObject receivedObject = (MyObject) receivedIntent.getSerializableExtra("myObject");

2. 传递数组:
   - 通过 Intent 传递数组。
// 在发送端
String[] stringArray = {"Apple", "Banana", "Orange"};
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("stringArray", stringArray);
startActivity(intent);

// 在接收端
Intent receivedIntent = getIntent();
String[] receivedArray = receivedIntent.getStringArrayExtra("stringArray");

3. 传递 ArrayList:
   - 通过 Intent 传递 ArrayList。
// 在发送端
ArrayList<String> stringList = new ArrayList<>();
stringList.add("Red");
stringList.add("Green");
stringList.add("Blue");
Intent intent = new Intent(this, SecondActivity.class);
intent.putStringArrayListExtra("stringList", stringList);
startActivity(intent);

// 在接收端
Intent receivedIntent = getIntent();
ArrayList<String> receivedList = receivedIntent.getStringArrayListExtra("stringList");

4. 传递复杂对象数组:
   - 通过 Intent 传递包含自定义对象的数组。
// 在发送端
MyObject[] objectArray = {new MyObject("Alice", 30), new MyObject("Bob", 28)};
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("objectArray", objectArray);
startActivity(intent);

// 在接收端
Intent receivedIntent = getIntent();
MyObject[] receivedArray = (MyObject[]) receivedIntent.getSerializableExtra("objectArray");

5. 传递 Bundle:
   - 通过 Intent 传递 Bundle,Bundle 可以包含多个键值对。
// 在发送端
Intent intent = new Intent(this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putString("name", "Jane");
bundle.putInt("age", 22);
intent.putExtras(bundle);
startActivity(intent);

// 在接收端
Intent receivedIntent = getIntent();
Bundle receivedBundle = receivedIntent.getExtras();
String name = receivedBundle.getString("name");
int age = receivedBundle.getInt("age");

6. 传递序列化对象:
   - 对于一些复杂的对象,实现 Serializable 接口也是一种可行的方式。
// 在发送端
MySerializableObject serializableObject = new MySerializableObject("Tom", 26);
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("serializableObject", serializableObject);
startActivity(intent);

// 在接收端
Intent receivedIntent = getIntent();
MySerializableObject receivedObject = (MySerializableObject) receivedIntent.getSerializableExtra("serializableObject");

以上是一些关于传递复杂数据的示例。在选择使用 Serializable 还是 Parcelable 接口时,建议使用 Parcelable,因为它通常比 Serializable 更高效。Parcelable 被设计为在 Android 中更有效地传递对象,特别适用于大量数据的情况。


转载请注明出处:http://www.pingtaimeng.com/article/detail/15180/Android