, ) 它不一定是 ArrayL-6ren">
gpt4 book ai didi

android - Parcelable 对象 kotlin 中的 ArrayList>

转载 作者:搜寻专家 更新时间:2023-11-01 09:21:20 35 4
gpt4 key购买 nike

字符串数组的数组需要被分割。对象是这样的

data class Foo (
@SerializedName("bar") val bar: ArrayList<ArrayList<String>>,
)

它不一定是 ArrayList。也可以使用数组。

data class Foo (
@SerializedName("bar") val bar: Array<Array<String>>,
)

哪个更容易映射这个json数据就可以了

{
"bar": [
["a", "b"],
["a1", "b2", "c2"],
["a3", "b34", "c432"]
]
}

使用 kotlin experimental Parcelize 在使用 progaurd 编译时会导致应用程序崩溃

在“writeToParcel”中是怎么写的,在“constructor”中是怎么读的?

data class Foo (
@SerializedName("bar") val bar: ArrayList<ArrayList<String>>,
) : Parcelable {

constructor(source: Parcel) : this(
// ?????
)

override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
// ?????
}

}

最佳答案

你不能直接创建Parcelable对于 ListList直接,所以一种解决方案是创建一个你想要的子类 List作为Parcelable并将其作为最终列表类型。 如何?请查看以下内容:

让我们首先创建我们的内部字符串列表类,如下所示:

class StringList() : ArrayList<String>(), Parcelable {
constructor(source: Parcel) : this() {
source.createStringArrayList()
}

override fun describeContents() = 0

override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeStringList(this@StringList)
}

companion object {
@JvmField
val CREATOR: Parcelable.Creator<StringList> = object : Parcelable.Creator<StringList> {
override fun createFromParcel(source: Parcel): StringList = StringList(source)
override fun newArray(size: Int): Array<StringList?> = arrayOfNulls(size)
}
}
}

我们在这里所做的是创建我们的 ArrayList<String> parcelable 以便我们可以在任何端点使用它。

因此最终数据类将具有以下实现:

data class Foo(@SerializedName("bar") val bar: List<StringList>) : Parcelable {
constructor(source: Parcel) : this(
source.createTypedArrayList(StringList.CREATOR)
)

override fun describeContents() = 0

override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeTypedList(bar)
}

companion object {
@JvmField
val CREATOR: Parcelable.Creator<Foo> = object : Parcelable.Creator<Foo> {
override fun createFromParcel(source: Parcel): Foo = Foo(source)
override fun newArray(size: Int): Array<Foo?> = arrayOfNulls(size)
}
}
}

注意:这是基于O.P.的简单实现,您可以根据您的要求进行任何定制。

关于android - Parcelable 对象 kotlin 中的 ArrayList<ArrayList<String>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55056972/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com