In my Fragment
I have a custom view that extends LinearLayout
. Let's call it gallery
In that custom view I have 5 ImageView
. Each contains an image loaded from web.
When my Fragment
is no longer required I destroy references in onDestroyView()
@Override
public void onDestroyView() {
super.onDestroyView();
gallery = null;
}
I noticed, that my app leaks memory and using DDMS and MAT I found that those 5 Bitmap
in those ImageView
s are still in memory. Well that's no good. So on the next step I did this in my mini gallery
@Override
protected void onDetachedFromWindow() {
super.onDestroyView();
imageView1 = null;
...
imageView5 = null;
}
That didn't help either. On my last attempt I did this
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
imageView1.setImageBitmap(null);
imageView1 = null;
...
imageView5.setImageBitmap(null);
imageView5 = null;
}
That helped. Memory was freed and memory leaks were plugged up.
Now my question is - why? Why, when my gallery was not referenced by anything it was not GC
'ed? And even more - when ImageView
was not references it's content - Bitmap - was never GC
'ed? Should I forcefully clean image bitmap?
I noticed that in other custom views where ImageView
is used I had a similar problem. What are best practices for such cases?