Android HashMap in Bundle?

后端 未结 7 2356
眼角桃花
眼角桃花 2020-12-02 11:57

The android.os.Message uses a Bundle to send with it\'s sendMessage-method. Therefore, is it possible to put a HashMap inside a

相关标签:
7条回答
  • 2020-12-02 12:35

    I am using my kotlin implementation of Parcelable to achieve that and so far it works for me. It is useful if you want to avoid the heavy serializable.

    Also in order for it to work, I recommend using it with these

    Declaration

    class ParcelableMap<K,V>(val map: MutableMap<K,V>) : Parcelable {
        constructor(parcel: Parcel) : this(parcel.readMap(LinkedHashMap<K,V>()))
    
        override fun writeToParcel(parcel: Parcel, flags: Int) {
            parcel.writeMap(map)
        }
    
        override fun describeContents(): Int {
            return 0
        }
    
        companion object CREATOR : Parcelable.Creator<ParcelableMap<Any?,Any?>> {
            @JvmStatic
            override fun createFromParcel(parcel: Parcel): ParcelableMap<Any?,Any?> {
                return ParcelableMap(parcel)
            }
            @JvmStatic 
            override fun newArray(size: Int): Array<ParcelableMap<Any?,Any?>?> {
                return arrayOfNulls(size)
            }
        }
    
    }
    

    Use

    write

    val map = LinkedHashMap<Int, String>()
    val wrap = ParcelableMap<Int,String>(map)
    Bundle().putParcelable("your_key", wrap)
    

    read

    val bundle = fragment.arguments ?: Bundle()
    val wrap = bundle.getParcelable<ParcelableMap<Int,String>>("your_key")
    val map = wrap.map
    

    Don't forget that if your map K,V are not parceled by default they must implement Parcelable

    0 讨论(0)
提交回复
热议问题