gpt4 book ai didi

android - 为什么使用 Fragment#setRetainInstance(boolean)?

转载 作者:IT老高 更新时间:2023-10-28 13:21:26 26 4
gpt4 key购买 nike

我发现 Fragment#setRetainInstance(true) 令人困惑。这是从 Android Developer API 中提取的 Javadoc :

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.

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

最佳答案

How do you as a developer use this

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

and why does it make things easier?

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

关于android - 为什么使用 Fragment#setRetainInstance(boolean)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11160412/

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