Android 实现具有 hashmap 的 Parcelable 对象 [英] Android implement Parcelable object which has hashmap
本文介绍了Android 实现具有 hashmap 的 Parcelable 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的课程.
public class RateData {
Map<String, List<RateDTO>> rateMap;
}
public class RateDTO {
private String code;
private String name;
private String value;
}
现在我需要可打包这个 RateData 类.我认为我们不能把这个 rateMap
打包成普通变量.
Now I need parcelable this RateData class. I think we can not parcel this rateMap
as normal variable.
请给我一个如何做到这一点的例子.
Please give me an example how to do this.
推荐答案
你应该使 DateRTO
Parcelable
- 这应该是微不足道的.然后,
You should make DateRTO
Parcelable
- this should be trivial. Then,
Map<String, List<RateDTO>> map;
public void writeToParcel(Parcel out, int flags) {
out.writeInt(map.size());
for (Map.Entry<String, List<RateDTO>> entry : map.entrySet()) {
out.writeString(entry.getKey());
final List<RateDTO> list = entry.getValue();
final int listLength = list.size();
out.writeInt(listLength);
for (RateDTO item: list) {
out.writeParcelable(item, 0);
}
}
}
private MyParcelable(Parcel in) {
final int size = in.readInt();
for (int i = 0; i < size; i++) {
final String key = in.readString();
final int listLength = in.readInt();
final List<RateDTO> list = new ArrayList<RateDTO>(listLength);
for (int j = 0; j < listLength; j++) {
final RateDTO value = in.readParcelable(ParentClass.class.getClassLoader());
list.add(value);
}
map.put(key, list);
}
}
我还没有测试过代码,但我相信它应该接近 OK.请注意,如果您的地图相对较大,则此解决方案不是特别好.
I haven't tested the code, but I believe it should be close to OK. Note that this solution is not particularly good if your map is relatively large.
这篇关于Android 实现具有 hashmap 的 Parcelable 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文