• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

android - 理解 Fragment 的 setRetainInstance(boolean)

[复制链接]
菜鸟教程小白 发表于 2022-8-1 01:19:52 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

从文档开始:

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.

我有一些问题:
  • 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/

    回复

    使用道具 举报

    懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    关注0

    粉丝2

    帖子830918

    发布主题
    阅读排行 更多
    广告位

    扫描微信二维码

    查看手机版网站

    随时了解更新最新资讯

    139-2527-9053

    在线客服(服务时间 9:00~18:00)

    在线QQ客服
    地址:深圳市南山区西丽大学城创智工业园
    电邮:jeky_zhao#qq.com
    移动电话:139-2527-9053

    Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap