为什么要使用 Fragment#setRetainInstance(boolean)? [英] Why use Fragment#setRetainInstance(boolean)?

查看:21
本文介绍了为什么要使用 Fragment#setRetainInstance(boolean)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 Fragment#setRetainInstance(true) 令人困惑.这是从 Android 开发者 API 中提取的 Javadoc::><块引用>

public void setRetainInstance(布尔保留)

控制是否在 Activity 重新创建期间保留片段实例(例如来自配置更改).这只能用于不在后堆栈中的片段.如果设置,则重新创建 Activity 时片段生命周期会略有不同:

  • onDestroy() 不会被调用(但 onDetach() 仍然会被调用,因为片段正在与其当前活动分离).
  • onCreate(Bundle) 不会被调用,因为片段没有被重新创建.
  • onAttach(Activity) 和 onActivityCreated(Bundle) 仍会被调用.

问题:作为开发人员,您如何使用它,为什么它能让事情变得更容易?

解决方案

作为开发者,您如何使用它

调用setRetainInstance(true).我通常在 onCreateView()onActivityCreated() 中使用它.

<块引用>

为什么它让事情变得更容易?

它往往比 onRetainNonConfigurationInstance() 更简单,用于处理跨配置更改的数据保留(例如,将设备从纵向旋转到横向).未保留的片段在配置更改时被销毁和重新创建;保留的片段不是.因此,那些保留的片段所持有的任何数据都可用于配置更改后的活动.

I find Fragment#setRetainInstance(true) confusing. Here is the Javadoc, extracted from the Android Developer API:

public void setRetainInstance (boolean retain)

Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated:

  • onDestroy() will not be called (but onDetach() still will be, because the fragment is being detached from its current activity).
  • onCreate(Bundle) will not be called since the fragment is not being re-created.
  • onAttach(Activity) and onActivityCreated(Bundle) will still be called.

Question: How do you as a developer use this, and why does it make things easier?

解决方案

How do you as a developer use this

Call setRetainInstance(true). I typically do that in onCreateView() or onActivityCreated(), where I use it.

and why does it make things easier?

It tends to be simpler than onRetainNonConfigurationInstance() for handling the retention of data across configuration changes (e.g., rotating the device from portrait to landscape). Non-retained fragments are destroyed and recreated on the configuration change; retained fragments are not. Hence, any data held by those retained fragments is available to the post-configuration-change activity.

这篇关于为什么要使用 Fragment#setRetainInstance(boolean)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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