gpt4 book ai didi

android - android 中 onCreate fragment 中的 setRetainInstance(true)

转载 作者:太空狗 更新时间:2023-10-29 15:38:31 29 4
gpt4 key购买 nike

我的 fragment 中没有任何上下文,所以我在 UI fragment 中使用 setRetainInstance(true)。谁能告诉我这是否是正确的方法?另外,我们基本上应该在哪里调用 setRetainInstance 方法?我的意思是在 onCreateonActivityCreated 等中。

最佳答案

简介:setRetainInstance(boolean)

当您查看 Reference ,你看:

  • onDestroy() 不会被调用(但 onDetach() 仍然会被调用,因为 fragment 正从其当前 Activity 中分离出来)。
  • 不会调用 onCreate(Bundle),因为不会重新创建 fragment 。
  • onAttach(Activity)onActivityCreated(Bundle) 仍将被调用

那么,我应该在哪里使用这个方法呢?

此方法用于在配置更改时保留一个 fragment 。您需要在其首次创建 时在 fragment 中设置此方法。当你看到上面的onAttachonActivityCreated 轮换后仍然会被调用时,不要在里面设置方法,因为你会再次调用它。没用的...!最好的方法是在 onCreate 方法中调用 setRetainInstance,因为这最后一个在更改旋转后将不会再次调用

正确的使用方法是什么?

一切都取决于您想要什么以及如何处理您的 FragmentActivity 和 fragment 。我会用 a quote 回答亚历克斯·洛克伍德:

Retained fragments can be quite useful for propagating state information — especially thread management — across activity instances. For example, a fragment can serve as a host for an instance of Thread or AsyncTask, managing its operation. See my blog post on this topic for more information.

In general, I would treat it similarly to using onConfigurationChanged with an Activity... don't use it as a bandaid just because you are too lazy to implement/handle an orientation change correctly. Only use it when you need to.

关于android - android 中 onCreate fragment 中的 setRetainInstance(true),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21203948/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com