android intent传递对象
时间: 2023-09-10 17:08:14 浏览: 60
要在 Android 中使用 Intent 传递对象,你需要确保该对象序列化,然后将其放入 Intent 的 extras 中。
首先,你需要确保对象实现了 Serializable 或 Parcelable 接口。Parcelable 更高效,但是 Serializable 更容易实现。以下是一个实现 Serializable 接口的示例类:
```
public class MyObject implements Serializable {
private int id;
private String name;
public MyObject(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
```
然后,在发送 Intent 时,你需要将对象放入 extras 中:
```
MyObject myObject = new MyObject(1, "John");
Intent intent = new Intent(this, MyActivity.class);
intent.putExtra("myObject", myObject);
startActivity(intent);
```
最后,在接收 Intent 的 Activity 中,你可以从 extras 中获取对象:
```
MyObject myObject = (MyObject) getIntent().getSerializableExtra("myObject");
```
如果你的对象实现了 Parcelable 接口,你可以使用以下代码将其放入 Intent 的 extras 中:
```
MyObject myObject = new MyObject(1, "John");
Intent intent = new Intent(this, MyActivity.class);
intent.putExtra("myObject", myObject);
startActivity(intent);
```
最后,在接收 Intent 的 Activity 中,你可以从 extras 中获取对象:
```
MyObject myObject = getIntent().getParcelableExtra("myObject");
```