android - 使用 Fragment 的 setRetainInstance(true) 真的是处理旋转变化的好习惯吗

标签 android

我指的是Why use Fragment#setRetainInstance(boolean)?

我这样问的原因是 Activity 来处理旋转,Official Activity Documentation鼓励我们让 Activity 在轮换期间关闭并重新启动。

android:configChanges Lists configuration changes that the activity will handle itself. When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with this attribute will prevent the activity from being restarted. Instead, the activity remains running and its onConfigurationChanged() method is called. Note: Using this attribute should be avoided and used only as a last-resort. Please read Handling Runtime Changes for more information about how to properly handle a restart due to a configuration change.

任何更改此 Activity 默认行为的尝试似乎都是不好的做法。为了避免Activity在重启过程中重新加载耗时的数据结构,我们使用了onRetainNonConfigurationInstancegetLastNonConfigurationInstance。 - Official Handling Runtime Changes

但是,当谈到在 Fragment 中处理轮换时,Google 是否给了我们不同的建议?他们不希望我们关闭并重新启动 Fragment?

public Object onRetainNonConfigurationInstance ()

This method was deprecated in API level 13. Use the new Fragment API setRetainInstance(boolean) instead; this is also available on older platforms through the Android compatibility package.

  1. 为什么 Google 鼓励我们在轮换期间关闭并重新启动 Activity,但鼓励我们在轮换期间保留 Fragment?
  2. 如果 setRetainInstance(true) 擅长处理轮换,Google 为什么不将其作为 Fragment 的默认行为?

最佳答案

  • 配置变化:当屏幕突然变得更宽且高度更小(典型的风景)时,视觉组件倾向于更新其显示并更智能地使用可用的屏幕.配置更改的另一个示例是用户滑动硬件键盘、更改设备语言等。为什么要重新开始:

    • Android 组件偏爱声明式布局,您可以加载一堆 XML 布局,然后从那里开始工作。查找每个 View 并实时重新排列/更新它会很麻烦,更不用说重新连接所有事件处理程序和其他自定义 View 代码了。它更容易重新加载另一组布局文件。

    • 另外,在 Android 中,Activity 有点受系统支配,所以很自然地,Activity 生命周期的设计(和推荐)它能够按需重新创建自己,任何时候,只要就像它被摧毁之前一样。此模式适用于所有重新启动,以及由于配置更改而导致的重新启动。如果您使您的 Activity 和 fragment 能够保持永久状态,那么配置更改将不是什么大问题。

    • 保留状态数据(模型),而不是显示它的东西(UI 和 View )。

  • setRetainInstance(true):建议仅与不包含任何引用的 fragment 一起使用,这些 fragment 将在旋转时重新创建。这意味着您不应该在任何包含上下文、 View 等的 fragment 上使用它。典型的视觉 fragment 可以。但它对于保存对象的 fragment 非常有用,如运行线程、异步任务、数据集合、加载的 Assets 、获取的结果等。此方法有助于将非可视 fragment 用作可拆卸的持有者,用于 Activity 的非上下文相关对象.

关于android - 使用 Fragment 的 setRetainInstance(true) 真的是处理旋转变化的好习惯吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15066075/

相关文章:

具有行间距的 Android spannable 字符串

android - Activity.onDestroy 幕后花絮 那么 destroy 的真正含义是什么?

android - 即使应用被杀死,声音仍会继续播放

java - 添加工具栏不起作用

android - 错误 : No resource identifier found for attribute 'showsAsAction' in package 6

android - 如何更改android项目中的SDK版本

java - 如何在xml android中绘制四分之一圆

android - 执行查询导致 "no such column"异常

Android Content Provider 和多对多数据库关系

java - 从 ArrayList 中检索数据