为什么使用片段#setRetainInstance(布尔)? [英] Why use Fragment#setRetainInstance(boolean)?

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

问题描述

我觉得片段#setRetainInstance(真)混淆。下面是Javadoc中,从<一个提取href="http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance%28boolean%29">Android开发者API :

  

公共无效 setRetainInstance (布尔保留)

     

控制跨越活动再创造一个片段实例是否被保留(例如,从一个配置变化)。这只能用于与碎片不会在后面栈。如果设置,该片段的生命周期会略有不同,当一个活动被重建:

     
      
  • 的onDestroy()将不会被调用(但onDetach()仍然将是,因为该片段将被从其当前活动分离的)。
  •   
  • 的onCreate(捆绑)将不会被调用,因为没有被重新创建的片段。
  •   
  • onAttach(活动)和onActivityCreated(捆绑)的仍然被调用。
  •   

问:你如何为开发者利用这一点,为什么它使事情更容易

解决方案
  

你怎么作为一名开发人员使用此

呼叫 setRetainInstance(真)。我通常做,在 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.

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

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