Android中onCreate片段中的setRetainInstance(true) [英] setRetainInstance(true) in onCreate fragment in android

查看:47
本文介绍了Android中onCreate片段中的setRetainInstance(true)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有在片段中保留任何上下文,因此我在UI片段中使用了 setRetainInstance(true).谁能告诉我这是正确的方法吗?另外,我们应该在哪里基本上调用 setRetainInstance 方法?我的意思是 onCreate onActivityCreated 等.

I am not holding any context in my fragment so I am using setRetainInstance(true) in UI fragment. can any one tell me whether this is the correct approach? Also where we should basically call setRetainInstance method? I mean in onCreate or onActivityCreated etc.

推荐答案

我将尝试尽可能简单地说明这一点.

I'll try to put it as simply as possible.

您的片段可能包含UI元素-如:

Your fragment, probably, holds UI elements - like:

私有TextView mView

这些UI元素使用 LayoutInflater 类实例在片段的 onCreateView(LayoutInflater,ViewGroup,Bundle)方法中初始化.

These UI elements get initialized in onCreateView(LayoutInflater, ViewGroup, Bundle) method of a fragment, using the LayoutInflater class instance.

但是此 LayoutInflater 实例使用 Activity 的上下文来填充您的资源.因此,如果您的UI窗口小部件存储在您的片段类中,则它们隐式拥有关联活动的 Context -即,您通过提交 FragmentManager 将其附加到的活动code>的交易.

But this LayoutInflater instance uses Activity's context to inflate your resources. So if your UI widgets are stored in your fragment class, they implicitly possess the Context of the associated activity - that is, the activity to which you've attached it to by commiting FragmentManager's transaction.

现在想象一下配置发生了变化(例如屏幕旋转). Activity (活动)被销毁,并创建了一个新活动.通常,应将旧的 Activity context 进行垃圾回收.但是您保留的片段实例通过您存储的每个UI元素对此上下文拥有 strong参考,因此该上下文,并且不应被垃圾收集.发生内存泄漏.

Now imagine a configuration change occures (screen rotation, for example). Activity gets destroyed and a new one is created. Old Activity's context normally should be garbage collected. But your retained fragment instance holds a strong reference to this context via each one of your stored UI elements, and thus this context is "reachable" in terms of GC, and should not be garbage-collected. A memory leak occurs.

这就是为什么保留的实例片段不应用作UI片段的原因.

That's why retained instance fragments should not be used as UI-fragments.

请记住-即使您不存储 Context 对象的引用,例如 private Context context (这就是您要的内容),您可能会以多种可能性泄漏此上下文.

Just remember - even if you do not store a reference to Context object, like private Context context (that's what you asked), you might leak this context in a plenty of possibilities.

这篇关于Android中onCreate片段中的setRetainInstance(true)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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