destroy view(layout)

19,757

Solution 1

You can remove a View from a ViewGroup, but there is no way to manually destroy a view. If you are getting memory leaks, it is usually because you are holding a long-lived reference to your Context outside of your Views.

  1. Don't store anything that has a Context in a static field (i.e. Drawables - Bitmaps are fine)
  2. Remove all handlers, clear all timers
  3. Don't hold onto Contexts in Threads/AsyncTasks, or if you do make sure they're weak-referenced.

It is fine for Views to contain information relating to other Views (i.e. the Context of another view) since all views are destroyed -- it is most likely because the Context is held onto by something (and the context has a handle on most things - i.e. all of your Views) that you are unable to free the memory.

Solution 2

Do you have any Handler/Messages in your Views which you may need to stop?

I had a similar issue whereby I was sending messages in a View periodically for an animation. I needed to stop/ignore the messages and stop queuing more once the activity OnDestroy() was triggered.

Share:
19,757
jojackso
Author by

jojackso

Android / Java developer.

Updated on June 04, 2022

Comments

  • jojackso
    jojackso almost 2 years

    I'm fighting with memory leaks now. So i'm curious if there any way to manually destroy view(in activity onDestroy method) ? The whole layout(activity contentView) is a bit complex because of parent-child references, context references, tags, etc.

    GC is not able to collect my layout now. And the problem is hiding deeply in view structure... So the only way to find it - is to try destroy leaf views manualy so at some moment GC will collect root view and give me a knowlege of where is problem located.

    My layout structure: ViewFlipper(RelativeLayout, ListView(ViewFlipper(RelativeLayout, RelativeLayout)))

  • CatalystNZ
    CatalystNZ about 13 years
    And yes, I realize your question was about forcing the view to free, but I don't know if that is possible. At least, I've never seen any exposed memory management calls. I wish there was.