gpt4 book ai didi

android - Kotlin,如何使hashMap可拆分

转载 作者:行者123 更新时间:2023-12-02 13:19:12 24 4
gpt4 key购买 nike

拥有一个变量是hashMap <IntRange, String>,并且需要以可包裹的形式放入包中,以便在onSaveStateInstance()/ onCreateView()中进行保存和恢复:

val map: HashMap<IntRange, String>? = hashMapOf(IntRange(0, 4) to "x", IntRange(5, -1) to "y")

并做
//saving:
outState.putParcelable("saved_map", map)

...
//retrieving:
val map = bundle.getParcelable("saved_map")

最佳答案

我仍然建议使用包装器类,因为它在Kotlin中比在Java中简单得多。 @Parcelize supports HashMap ,问题在于它不支持IntRange(或至少未列出)。但是基于那里的示例,看来这应该可行:

object IntRangeParceler : Parceler<IntRange> {
override fun create(parcel: Parcel) = IntRange(parcel.readInt(), parcel.readInt())

override fun IntRange.write(parcel: Parcel, flags: Int) {
parcel.writeInt(value, start)
parcel.writeInt(value, endInclusive)
}
}

@Parcelize
@TypeParceler<IntRange, IntRangeParceler>()
class IntRangeStringMap(val value: HashMap<IntRange, String>)

你的电话变成
outState.putParcelable("saved_map", IntRangeStringMap(map))
val map = bundle.getParcelable("saved_map").value

您甚至可以通过添加扩展功能使它看起来像您想要的方式。

关于android - Kotlin,如何使hashMap可拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60383863/

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