保留数据的 Android 片段 [英] Android Fragments Retaining Data

查看:34
本文介绍了保留数据的 Android 片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当 Fragment 的活动经历一个 onCreate/Destroy 循环(如 Rotation)时,如何最好地在 Fragment 中保留数据?

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

在我们的设置中,我们可能会将大型列表从我们的服务器加载到片段自定义列表适配器中,我们希望通过不让它们在轮换时重新加载来平滑用户体验.我们在设置片段 retainInstance=true; 时遇到的问题;是我们的适配器引用了原始活动的上下文,因此会泄漏内存.我们可以将数据存储在片段中并重新创建适配器吗?如果是这样,那真的是正确的做法吗?

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?

下一个想法是将数据存储到会话单例对象中并在轮换后检索,这会带来一些陈旧数据的问题,但我们可以轻松克服.

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.

我看到的另一种选择,似乎是*最好的解决方案,是将数据保存到一个包中,并在旋转后恢复到新的片段中;但是,我们有相当多的对象需要在整个应用程序中存储,并且我们的一些对象很复杂,包含列表、多种类型,并且很难打包.有没有更好的解决方案,还是我们必须硬着头皮让它们可包裹?

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?

推荐答案

只是防止 Activity 在旋转时重新创建自己(等).添加

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

android:configChanges="keyboardHidden|orientation|screenSize"

到您的 AndroidManifest.xml 中的 Activity 定义.那么就不需要在轮换时保存任何东西了.

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.

这篇关于保留数据的 Android 片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆