list实现Parcelable
时间: 2023-07-20 08:07:26 浏览: 50
要实现一个可序列化的 `List`,需要让 `List` 实现 `Parcelable` 接口。具体步骤如下:
1. 在 `List` 的实现类中添加一个静态内部类 `ListEntry`。
```java
public class MyList<T> implements Parcelable {
private List<T> list;
public static class ListEntry<T> implements Parcelable {
private T entry;
public ListEntry(T entry) {
this.entry = entry;
}
public T getEntry() {
return entry;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(entry);
}
public static final Creator<ListEntry> CREATOR = new Creator<ListEntry>() {
@Override
public ListEntry createFromParcel(Parcel in) {
return new ListEntry<>(in.readValue(null));
}
@Override
public ListEntry[] newArray(int size) {
return new ListEntry[size];
}
};
}
// ...
}
```
2. 在 `List` 的实现类中实现 `Parcelable` 接口的方法。
```java
public class MyList<T> implements Parcelable {
private List<T> list;
public MyList(List<T> list) {
this.list = list;
}
protected MyList(Parcel in) {
int size = in.readInt();
list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
ListEntry<T> entry = in.readParcelable(null);
list.add(entry.getEntry());
}
}
@Override
public void writeToParcel(Parcel dest, int flags) {
int size = list.size();
dest.writeInt(size);
for (int i = 0; i < size; i++) {
dest.writeParcelable(new ListEntry<>(list.get(i)), flags);
}
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<MyList> CREATOR = new Creator<MyList>() {
@Override
public MyList createFromParcel(Parcel in) {
return new MyList(in);
}
@Override
public MyList[] newArray(int size) {
return new MyList[size];
}
};
// ...
}
```
3. 在 `List` 的实现类中添加一个静态工厂方法 `fromList`,用于从普通的 `List` 转换为实现了 `Parcelable` 接口的 `MyList`。
```java
public class MyList<T> implements Parcelable {
private List<T> list;
public static <T> MyList<T> fromList(List<T> list) {
return new MyList<>(list);
}
// ...
}
```
现在,就可以使用 `MyList.fromList(list)` 方法将普通的 `List` 转换为实现了 `Parcelable` 接口的 `MyList`,并将其传递给其他组件了。