未删除的ViewTreeObserver侦听器会导致内存泄漏吗? [英] Can a not removed ViewTreeObserver listener cause memory leaks?

查看:250
本文介绍了未删除的ViewTreeObserver侦听器会导致内存泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 OnGlobalLayoutListener 监听视图的布局更改:

I'm listening to layout changes of a view using an OnGlobalLayoutListener:

view.getViewTreeObserver().addOnGlobalLayoutListener(myListener);

由于只要对该视图存在,我就对该侦听器的事件感兴趣,因此我无需调用 removeOnGlobalLayoutListener(myListener).

Since I'm interested in the events of this listener as long as the view exists I see no need to call removeOnGlobalLayoutListener(myListener).

这是否可能导致内存泄漏,或者是否将侦听器垃圾与视图一起收集?假设侦听器拥有对该视图的引用.

Can this cause memory leaks or is the listener garbage collected along with the view? Assume that the listener holds a reference to the view.

背景是我想创建一个模块,该模块可以附加到某些视图,并根据布局更改进行处理.如果不需要删除,则其创建就像 new FancyModule(theView)一样简单,然后构造函数负责绑定侦听器.如果必须删除,则必须实现一个我想防止的析构函数方法.

The backgound is that I want to create a module that can be attached to certain views and does stuff based on layout changes. If removing is not necessary its creation would be just as simple as new FancyModule(theView) and the constructor then takes care of binding the listener. If removal is necessary I'd have to implement a destructor method which I'd like to prevent.

推荐答案

潜在的内存泄漏仅取决于您的体系结构.

Potential memory leak depends only on your architecture.

通常,最好不调用 removeOnGlobalLayoutListener(myListener). View 保存对 ViewTreeObserver 的引用,该视图保存对添加的 OnGlobalLayoutListener 的引用.如果您没有对侦听器的其他引用,则它是沿视图收集的垃圾.

Normally, it's fine not to call removeOnGlobalLayoutListener(myListener). View holds reference to ViewTreeObserver which holds reference to added OnGlobalLayoutListener. If you don't have another reference to the listener, it's garbage collected along the view.

现在,如果 OnGlobalLayoutListener 的实现保留对视图的引用,则仍然可以.对于Android的垃圾收集器来说,参考周期不是问题.

Now, if your implementation of OnGlobalLayoutListener holds reference to the view it is still fine. A reference cycle is not a problem for Android's garbage collector.

如果您有另一个持有对 OnGlobalLayoutListener 实现的引用的组件,则可能会产生问题.如果组件的生存期比视图长(例如,通过应用程序对象保存),则您会通过侦听器创建视图(和上下文)的内存泄漏.

A problem can be created if you have another component that holds reference to the OnGlobalLayoutListener implementation. If the component lives longer than the view (e.g. it is held via the application object) then you create a memory leak of the view (and context) through the listener.

重要的是在不再使用该视图时不要保留该视图.一种避免泄漏视图的简单方法是使用 WeakReference .

It is important to not hold the view when it's no longer used. A simple way how to avoid leaking the view is to use WeakReference.

这篇关于未删除的ViewTreeObserver侦听器会导致内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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