简体   繁体   English

如何保存在onSaveInstanceState上实现接口的列表

[英]How to save List that implements Interface on onSaveInstanceState

I have in my Activity : 我的Activity

List<IntManager> mt;
this.mt = new ArrayList<IntManager>();

Inside the mt list I have Objects that implement IntManager Interface, but they are let say type of Point (my custom class) mt列表中,我具有实现IntManager接口的对象,但可以说是Point类型(我的自定义类)

Now I want to save the this.mt in the onSaveInstanceState (Bundle outState) and restore it on onRestoreInstanceState 现在,我要将this.mt保存在onSaveInstanceState (Bundle outState) ,并将其还原到onRestoreInstanceState

How should I save it? 我该如何保存? Do IntManager have to implement Parcelable or my custom class Point ? 不要IntManager必须实现Parcelable或我的自定义类Point or any other? 还是其他?

是的,无论是IntManager和其使用的所有的成员字段必须实现Parcelable这样他们就可以被保存在Bundle

Yes, you could do it by implementing Parcelable and save them to the bundle 是的,您可以通过实施Parcelable并将其保存到捆绑包中来实现

or you could use a Json serializer to seriazlize the list of custom objects to a json string and save the string to the bundle. 或者,您可以使用Json序列化程序将自定义对象列表序列化为json字符串,然后将该字符串保存到包中。 For example, using GSon you could do it this way 例如,使用GSon,您可以这样做

java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<IntManager>>(){}.getType();
@Override
public void onSaveInstanceState(Bundle outState) {
   super.onSaveInstanceState(outState);
   String json = new Gson().toJson(mt, type);
   outState.putString("message", json);
}

and you can restore the instancestate from bundle 您可以从包中还原实例状态

List<IntManager> test=new Gson().fromJson(savedInstanceState.getString("message"), type);

hope this helps.. 希望这可以帮助..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM