如何包裹List< Int>与科特林 [英] How to parcel List<Int> with kotlin
本文介绍了如何包裹List< Int>与科特林的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过Bundle将数据类(包含int列表作为属性)传递给其他活动,因此我需要将Parcelable实现添加到我的数据类中. 关于如何打包此属性的任何想法吗?
I want to pass a data class (that contains list of int as a property) to other activity through Bundle and therefore i need to add Parcelable implementation to my data class. any idea about how to parcel this property?
data class Test(val id: Long, val files: List<Int>?) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readLong(),
TODO("files"))
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeLong(id)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Test> {
override fun createFromParcel(parcel: Parcel): Test {
return Test(parcel)
}
override fun newArray(size: Int): Array<Test?> {
return arrayOfNulls(size)
}
}
推荐答案
您可以将整数列表写为int[]
:
You can write a list of integers as int[]
:
parcel.writeIntArray(files.toIntArray())
确保回读时使用相同的数据结构:
Make sure you use the same data structure when reading back:
files = parcel.createIntArray().toList()
您可以通过跳过数组表示法来使用扩展功能来提高效率:
You could make it more efficient using extension functions by skipping the array representation:
parcel.writeIntList(files)
files = parcel.createIntList()
fun Parcel.writeIntList(input:List<Int>) {
writeInt(input.size) // Save number of elements.
input.forEach(this::writeInt) // Save each element.
}
fun Parcel.createIntList() : List<Int> {
val size = readInt()
val output = ArrayList<Int>(size)
for (i in 0 until size) {
output.add(readInt())
}
return output
}
这篇关于如何包裹List< Int>与科特林的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文