开发者

Is it safe for a view to reference the activity that's displaying it?

I have extended View and passed it an instance of my Activity so the view can access some member variables and methods.

But now I'm thinking this could be a potential memory leak, because even after the Activity is destroyed, it still has a reference to the view in a member variable, and vice versa. So the garbage collector may never clean them up.

However, I've seen in some开发者_StackOverflow社区 of the Google API demos and examples cases where they have passed the Activity to the View as a listener.


This is fine, remember that any ordinary View you create programatically with its constructor takes a Context as its argument- usually the Context you give the constructor is just this, or the Activity itself. So your View already has a reference to its Activity. You can also get this inside the View class using its getContext() method.

When the Activity is destroyed, it will remain in memory until the GC can remove it. But as part of its onDestroy method, it sets the reference to any Views it contains to null, and so on down the View tree. Then the GC can safely remove all its component Views. Once that is complete, there are no references left to the Activity and another GC pass may delete it.


All the View constructors take the Context as a parameter so they already have a reference. Maybe post the code for the custom view so we can review it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜