我activity跳转需要传递一个实体类,我应该怎么写
时间: 2024-03-17 11:41:41 浏览: 90
在Activity之间传递一个实体类,可以通过实现Serializable或Parcelable接口来实现。下面是两种方式的具体实现方法:
1. 实现Serializable接口:
实体类代码示例:
```java
import java.io.Serializable;
public class MyEntity implements Serializable {
private String name;
private int age;
public MyEntity(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
在Activity中传递实体类的代码示例:
```java
MyEntity entity = new MyEntity("Tom", 18);
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("entity", entity);
startActivity(intent);
```
在接收Activity中获取实体类的代码示例:
```java
MyEntity entity = (MyEntity) getIntent().getSerializableExtra("entity");
```
2. 实现Parcelable接口:
实体类代码示例:
```java
import android.os.Parcel;
import android.os.Parcelable;
public class MyEntity implements Parcelable {
private String name;
private int age;
public MyEntity(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
// 实现Parcelable接口的方法
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
public static final Creator<MyEntity> CREATOR = new Creator<MyEntity>() {
@Override
public MyEntity createFromParcel(Parcel in) {
return new MyEntity(in);
}
@Override
public MyEntity[] newArray(int size) {
return new MyEntity[size];
}
};
// 从Parcel中读取数据构造实体类对象
private MyEntity(Parcel in) {
name = in.readString();
age = in.readInt();
}
}
```
在Activity中传递实体类的代码示例:
```java
MyEntity entity = new MyEntity("Tom", 18);
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("entity", entity);
startActivity(intent);
```
在接收Activity中获取实体类的代码示例:
```java
MyEntity entity = getIntent().getParcelableExtra("entity");
```
这两种方式都可以用来在Activity之间传递实体类,具体使用哪种方式取决于实体类的大小和复杂度,以及开发者的个人喜好。
阅读全文