[英]What's the best way to preserve a model across android configuration changes?
In my application, I have a fragment which renders a model object fetched from the server. 在我的应用程序中,我有一个片段,呈现从服务器获取的模型对象。 The model class implements
Parcelable
so when the device is rotated, I save the model in onSaveInstanceState()
and then I load the model in onCreate()
. 模型类实现了
Parcelable
因此当旋转设备时,我将模型保存在onSaveInstanceState()
,然后在onCreate()
加载模型。 If the savedInstanceState
bundle does not contain the model in onCreate()
, I make the network request again. 如果
savedInstanceState
包在onCreate()
中不包含模型,则再次发出网络请求。
My question is: Is it better to preserve the state of the model by having it implement Parcelable
and saving it in onSaveInstanceState()
OR is it better to simply set the Fragment
's setRetainInstanceState(true)
. 我的问题是:是否有更好的有它实施保护模型的状态
Parcelable
并保存它onSaveInstanceState()
还是更简单地设定Fragment
的setRetainInstanceState(true)
。
In my opinion setInstanceState should be used only in special cases, while onSaveInstanceState() should be used as standard approach to keep fragment's state. 我认为setInstanceState仅应在特殊情况下使用,而onSaveInstanceState()应该用作保留片段状态的标准方法。 This is common way for keeping state of all Android's components.
这是保持所有Android组件状态的常用方法。 Keeping fragment in memory can lead to situations like strange views behavior and memory leaks.
在内存中保留碎片可能会导致诸如奇怪的视图行为和内存泄漏之类的情况。
API指南建议使用保留的无头数据片段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.