如何在Android中拆分通用数组列表?

问题描述 投票:0回答:1

我有这样的课程:(可以在here中找到完整的定义]

public class AList<T> {
    private ArrayList<T> list = new ArrayList<>();
}

这是一个类似于C#的通用列表。

我应如何将AList实施为Parcelable?我在网上找到了示例,但它们的数据类型已确定。我应该如何处理泛型类型?

这是我目前的尝试:

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeList(list);
}

protected AList(Parcel in) {
    list = in.readArrayList(null);
}

public static final Creator<AList> CREATOR = new Creator<AList>() {
    @Override
    public AList createFromParcel(Parcel in) {
        return new AList(in);
    }

    @Override
    public AList[] newArray(int size) {
        return new AList[size];
    }
};

但是构造函数会给我BadParcelableException

我也尝试过这个:

protected AList(Parcel in) {
    in.readList(list, T.class.getClassLoader());
}

但是T不能用作变量,所以我不知道如何解决此语法。

java android parcelable
1个回答
0
投票

为了使List可拆分,该List的每个元素都应实现Parcelable。因此,基本上,您可以将列表定义为ArrayList<Parcelable> list = new ArrayList<>()

SomeClass implements Parcelable {
...
}

几次测试:

list.add("test"); // error, String doesn't implement Parcelable
list.add(new SomeClass()); // fine
list.add(new android.location.Address(Locale.getDefault())); // fine

这通常用于将数据附加到Intent,例如:

Intent i = new Intent(this, SomeActivity.class)
i.putParcelableArrayListExtra("key", list);
© www.soinside.com 2019 - 2024. All rights reserved.