android.os.Message
使用Bundle
在其sendMessage方法中进行发送。因此,是否可以将HashMap
放到Bundle
中?
android.os.Message
使用Bundle
在其sendMessage方法中进行发送。因此,是否可以将HashMap
放到Bundle
中?
尝试如下:
Bundle extras = new Bundle();
extras.putSerializable("HashMap",hashMap);
intent.putExtras(extras);
并且在第二个Activity中
Bundle bundle = this.getIntent().getExtras();
if(bundle != null) {
hashMap = bundle.getSerializable("HashMap");
}
因为 HashMap 默认实现了Serializable
接口,所以您可以使用putSerializable
将其传递到Bundle中,并在其他Activity中使用getSerializable
获取。
protected void onSaveInstanceState(Bundle outState) {}
方法(而不是public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {}
方法)。@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("leftMaxima", leftMaxima);
outState.putSerializable("rightMaxima", rightMaxima);
}
在onCreate中接收它:
if (savedInstanceState != null) {
leftMaxima = (HashMap<Long, Float>) savedInstanceState.getSerializable("leftMaxima");
rightMaxima = (HashMap<Long, Float>) savedInstanceState.getSerializable("rightMaxima");
}
如果这是某种重复的回答,很抱歉 - 也许有人会发现它有用。 :)
如果您想发送捆绑中的所有键,您可以尝试
for(String key: map.keySet()){
bundle.putStringExtra(key, map.get(key));
}
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)
}
}
}
标签来编写。
val map = LinkedHashMap<Int, String>()
val wrap = ParcelableMap<Int,String>(map)
Bundle().putParcelable("your_key", wrap)
val bundle = fragment.arguments ?: Bundle()
val wrap = bundle.getParcelable<ParcelableMap<Int,String>>("your_key")
val map = wrap.map
K,V
不是默认的被包裹的,它们必须实现 Parcelable
。 public static Bundle mapToBundle(Map<String, Object> data) throws Exception {
Bundle bundle = new Bundle();
for (Map.Entry<String, Object> entry : data.entrySet()) {
if (entry.getValue() instanceof String)
bundle.putString(entry.getKey(), (String) entry.getValue());
else if (entry.getValue() instanceof Double) {
bundle.putDouble(entry.getKey(), ((Double) entry.getValue()));
} else if (entry.getValue() instanceof Integer) {
bundle.putInt(entry.getKey(), (Integer) entry.getValue());
} else if (entry.getValue() instanceof Float) {
bundle.putFloat(entry.getKey(), ((Float) entry.getValue()));
}
}
return bundle;
}
用Kotlin编写:
hashMap = savedInstanceState?.getSerializable(ARG_HASH_MAP) as? HashMap<Int, ValueClass>
putSerializable(ARG_HASH_MAP, hashMap)