【发布时间】:2018-07-20 20:26:34
【问题描述】:
在实现 Parcelable 的类中,它有一个 HashMap 成员。
Saw Parcelable 有
public final void readMap(Map outVal, ClassLoader loader),但找不到可以使用的样本。
如果通过展平地图并相应地写入/读取来做到这一点,如何从构造函数中的包裹中提取? (从 Parcelable 构建地图时出错,cannot access buildTheMap() before constructor is called)
class CachedData(val type: Int,
val name: String,
val details: HashMap<String, String) :
Parcelable {
constructor(parcel: Parcel) : this(
parcel.readInt(),
parcel.readString(),
// how to get the hashMap out of the parcel???
buildTheMap(parcel) //<=== cannot access buildTheMap() before constructor is called
)
fun buildTheMap(parcel: Parcel) :HashMap<String, String> {
val size = parcel.readInt()
val map = HashMap<String, String>()
for (i in 1..size) {
val key = parcel.readString()
val value = parcel.readString()
map[key] = value
}
return map
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(type)
parcel.writeString(name)
// how to write the HashMap<String, String> to the parcel
//parcel.???
parcel.writeInt(details.size)
for ((key, value) in details) {
parcel.writeString(key)
parcel.writeString(value)
}
}
override fun describeContents(): Int {
return 0
}
companion object {
@JvmField val CREATOR: Parcelable.Creator<CachedData> = object : Parcelable.Creator<CachedData>{
override fun createFromParcel(parcel: Parcel): CachedData {
return CachedData(parcel)
}
override fun newArray(size: Int): Array<CachedData?> {
return arrayOfNulls(size)
}
}
}
}
【问题讨论】:
标签: android kotlin hashmap parcelable