为什么使用片段#setRetainInstance(布尔)?布尔、片段、setRetainInstance

由网友(爱、到此为止)分享简介:我觉得片段#setRetainInstance(真)混淆。下面是Javadoc中,从Android开发者API :公共无效 setRetainInstance (布尔保留)控制跨越活动再创造一个片段实例是否被保留(例如,从一个配置变化)。这只能用于与碎片不会在后面栈。如果设置,该片段的生命周期会略有不同,当一个活动被重...

我觉得片段#setRetainInstance(真)混淆。下面是Javadoc中,从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.

阅读全文

相关推荐

最新文章