保存自定义对象的ArrayList的状态自定义、对象、状态、ArrayList

2023-09-04 10:42:09 作者:偷得浮生

我在我的活动成员变量,它是一个ArrayList。填充此ArrayList中的对象是物我已经定义了一个名为RatingItem。 RatingItem有几个成员瓦尔样的评价,评论,ID等。

I have a member variable in my Activity which is an ArrayList. The objects populating this ArrayList are objects I have defined called RatingItem. RatingItem has several member vars like rating, comment, id, etc.

我想保存此ArrayList中的onSaveInstanceState,因此它可以从onRestoreInstanceState被重新填充。什么是做到这一点的最好方法是什么?我从来没有救了这种复杂性对象的状态。

I would like to save this ArrayList in onSaveInstanceState so it can be repopulated from onRestoreInstanceState. What is the best way to do this? I've never saved the state of an object of this complexity.

感谢您的帮助

推荐答案

您也许应该有你的对象实施的 Parcelable 。基本上,你必须添加的方法来写,从了解您的对象的成员包裹,然后添加自定义的 CREATOR ,有一对夫妇的静态工厂方法内部类。有它的第一个链接页面上的演示,但它不是太难。

You should probably have your object implement Parcelable. Basically, you have to add methods to write and read the members of your object from a Parcel, and then add custom CREATOR inner class that has a couple of static factory methods. There's a demo of it on the first linked page, but it's not too hard.

然后,你可以保存在一个去与 Bundle.putParcelableArrayList() 。 (你必须投列表中,当你把它找回来用 Bundle.getParcelableArrayList() 但它会正常工作。)

Then you can just save the whole list in one go with Bundle.putParcelableArrayList(). (You'll have to cast the list when you get it back out with Bundle.getParcelableArrayList() but it will work fine.)