如何保存过程中方向变化Android中的状态,如果状态是由我的课吗?我的、状态、是由、过程中

2023-09-11 12:45:04 作者:? 嘲笑°oneself

我一直在寻找的Andr​​oid手柄的方向变化我的应用程序的方式(我发现它在重启方向变化的mainactivity。我已经看到了,你可以重写方法

I was looking at the way Android handles orientation change for my application (I discovered that it restarts the mainactivity on orientation change. I've seen that you can override the method

protected void onSaveInstanceState(Bundle outState)

要保存的东西,然后让在ONSTART。问题是,我有我的观点与自定义的对象,并使用自定义适配器列表视图。一切都在这些对象的ArrayList,但我注意到,你不能把任意对象的包!那么,如何保存状态?

To save stuff, then have the in onStart. The problem is that I've my view with custom objects and a listview using a custom adapter. Everything is in a ArrayList of these objects, but I've noticed that you can't put arbitrary objects in the bundle! So how do I save the state?

推荐答案

编辑:在较新的Andr​​oid版本和兼容性库,retained片段通常处理保持高价到再造的数据通过活动破坏/创建活着的最好方式。正如戴安娜指出,保持nonconfiguration数据对于优化之类的东西生成缩略图是很好的保存性能方面的原因而不能正常工作,如果他们需要重做关键你的活动 - 这是不能代替正确保存和恢复活动状态。

On newer versions of Android and with the compatibility library, retained fragments are usually the best way to handle keeping expensive-to-recreate data alive across activity destruction/creation. And as Dianne pointed out, retaining nonconfiguration data was for optimizing things like thumbnail generation that are nice to save for performance reasons but not critical to your activity functioning if they need to be redone - it's not a substitute for properly saving and restoring activity state.

但回来时,我第一次在2010年回答了这个: 如果您想保留自己的(非视图状态)的数据,你其实可以通过任意对象专门为导向改变使用 onRetainNonConfigurationInstance()。请参见这个Android开发者博客帖子。只是要小心,不要把任何意见或其他引用了pre-旋转语境/活动在您传递对象,否则你会prevent被垃圾收集的对象,并最终可能耗尽内存(这就是所谓的背景下的泄漏)。

But back when I first answered this in 2010: If you want to retain your own (non view-state) data, you can actually pass an arbitrary object specifically for orientation changes using onRetainNonConfigurationInstance(). See this Android Developers blog post. Just be careful not to put any Views or other references to the pre-rotation Context/Activity in the object you pass, or you'll prevent those objects from being garbage collected and may eventually run out of memory (this is called a context leak).