Android的碎片保留数据碎片、数据、Android

2023-09-12 23:00:17 作者:四逼青年、

怎样才能最好的保留片段中的数据作为其活动将经历一个的onCreate /销毁周期就像从旋转?

How does one best retain data within a Fragment as its activity goes through an onCreate/Destroy cycle like from Rotation?

在我们的设置,我们已经从我们的服务器装入片段自定义列表适配器潜在的大名单,我们希望通过不使他们重新加载旋转理顺UX。我们曾与设置片段retainInstance =真正的问题;是我们的适配器有一个参照原有活动的范围内,因此会造成内存泄漏。难道我们只是将数据存储在片段并重新创建适配器; AMD如果是的话是真的正确的做法?

In our setup we have potentially large lists loaded from our servers into the fragments custom list adapter and we want to smooth out the UX by not making them reload on rotation. The problem we had with setting the fragment retainInstance=true; is that our adapter has a reference to the context of the original activity and would therefore leak memory. Could we just store the data in the fragment and re-create the adapter; amd if so is that really proper practice?

接下来的想法是将数据存储到一个会话singleton对象和旋转其中presents一些问题与陈旧的数据之后,检索,但我们可以很容易地克服。

The next idea is to store the data into a session singleton object and retrieve after rotation which presents a few problems with stale data but we can easily overcome.

另一种选择我看,这似乎是它是*最好的解决办法,是将数据保存到一个包,并恢复到旋转后的新片段;但是,我们有相当这将需要一些对象来存储整个应用程序和我们的一些对象是复杂的,包含列表,多种类型,而且将是一个痛苦,使parcelable。有没有更好的解决方案,或者说,我们必须咬紧牙关,使他们Parcelable?

The other alternative I see, that seems like it is the *best solution, is to save the data into a bundle and restore into the new fragment after rotation; However, we have quite a few objects that would need to be stored throughout the app and some of our objects are complex, contain lists, multiple types, and would be a pain to make parcelable. Is there a better solution or do we have to bite the bullet and make them Parcelable?

推荐答案

只需prevent活动从旋转(等)重新本身。添加

Just prevent the Activity from recreating itself on rotation (etc). Add

android:configChanges="keyboardHidden|orientation|screenSize"

在你的Andr​​oidManifest.xml中的活动定义。那么就没有必要节省旋转什么。

to your Activity definition in your AndroidManifest.xml. Then there's no need for saving anything on rotation.

编辑:

如果你不喜欢这种解决办法,然后你有没有选择,只能使用的onSaveInstanceState机制。如果你有复杂的数据,只是让你的类序列化,并将其添加到捆绑的方式。

If you don't like that solution then you've got no choice but to use the onSaveInstanceState mechanism. If you've got complex data, just make your classes Serializable and add them to the Bundle that way.