OGeek|极客世界-中国程序员成长平台

标题: android - 理解 Fragment 的 setRetainInstance(boolean) [打印本页]

作者: 菜鸟教程小白    时间: 2022-8-1 01:19
标题: android - 理解 Fragment 的 setRetainInstance(boolean)

从文档开始:

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:


我有一些问题:
  • fragment 是否也保留其 View ,或者会在配置更改时重新创建? “保留”究竟是什么意思?
  • 当用户离开activity时,fragment会被销毁吗?
  • 为什么它不适用于后堆栈上的 fragment ?
  • 在哪些用例中使用此方法有意义?


  • Best Answer-推荐答案


    首先查看my post在保留的 fragment 上。它可能会有所帮助。

    现在回答你的问题:

    Does the fragment also retain its view state, or will this be recreated on configuration change - what exactly is "retained"?



    是的,Fragment的状态将在配置更改期间保留。具体来说,“保留”意味着 fragment 不会在配置更改时被销毁。也就是说,Fragment即使配置更改导致底层 Activity 也会保留被摧毁。

    Will the fragment be destroyed when the user leaves the activity?



    就像 Activity年代,Fragment s 可能在内存资源不足时被系统销毁。您是否让 fragment 在配置更改时保留其实例状态不会影响系统是否会破坏 Fragment s 一旦你离开 Activity .如果您离开 Activity (即按主页按钮),Fragment s 可能会或可能不会被销毁。如果您离开 Activity通过按下后退按钮(因此,调用 finish() 并有效地销毁 Activity ),所有 Activity附上 Fragment s 也会被销毁。

    Why doesn't it work with fragments on the back stack?



    不支持它可能有多种原因,但对我来说最明显的原因是 Activity持有对 FragmentManager 的引用,以及 FragmentManager管理后台堆栈。也就是说,无论您是否选择保留您的 Fragment s 与否,Activity (因此 FragmentManager 的后台堆栈)将在配置更改时被销毁。它可能不起作用的另一个原因是,如果允许保留 fragment 和非保留 fragment 都存在于同一个 backstack 上,事情可能会变得棘手。

    Which are the use cases where it makes sense to use this method?



    保留的 fragment 对于跨 Activity 实例传播状态信息(尤其是线程管理)非常有用。例如, fragment 可以作为 Thread 实例的主机。或 AsyncTask ,管理其操作。见 my blog post有关此主题的更多信息。

    一般来说,我会像使用 onConfigurationChanged 一样对待它。与 Activity ...不要仅仅因为您懒得正确实现/处理方向更改而将其用作创可贴。仅在需要时使用它。

    关于android - 理解 Fragment 的 setRetainInstance(boolean),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11182180/






    欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4