Reputation: 720
While building a Dialog which loads content view layout (setContentView) I have noticed a weird thing: The loaded layout has an ImageView with background of this Dialog:
<ImageView android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/preloader_bg_small"
android:id="@+id/background_img"
/>
Each time the dialog shows (in different activities) it drains memory (30mb) the image itself is 290k jpg loaded from local resource and NEVER gets released
I have tried to load the image programmatically:
((ImageView)dialog.findViewById(R.id.background_img)).setImageResource(R.drawable.preloader_bg_small);
and then unloading it before the dismiss on the dialog
((ImageView)dialog.findViewById(R.id.background_img)).setImageDrawable(null);
But then the memory gets released only after the activity is closed and not immediately.
Is there a way releasing the memory? Why is ImageView behaves this way?
Thanks for help!
Upvotes: 1
Views: 3264
Reputation: 2114
An exemplary way to recycle a BitmapDrawable
resource of an ImageView
is using the following function :
protected void recycleDefaultImage() {
Drawable imageDrawable = imageView.getDrawable();
imageView.setImageDrawable(null); //this is necessary to prevent getting Canvas: can not draw recycled bitmap exception
if (imageDrawable!=null && imageDrawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = ((BitmapDrawable) imageDrawable);
if (!bitmapDrawable.getBitmap().isRecycled()) {
bitmapDrawable.getBitmap().recycle();
}
}
}
Upvotes: 0
Reputation: 720
Although its still weird solved in following way:
loading image by setting drawable and not resource directly:
((ImageView)dialog.findViewById(R.id.background_img)).setImageDrawable(getResources().getDrawable(R.drawable.preloader_bg_small));
and releasing it from memory by setting drawable to null
ImageView background_image = ((ImageView) dialog.findViewById(R.id.background_img));
background_image.setImageDrawable(null);
Upvotes: 1
Reputation: 4981
Try ((ImageView)dialog.findViewById(R.id.background_img)).setImageResource(android.R.color.transparent);
But it doesn't seem the image view problem. Your activity keeps link to image. Please give more code.
Upvotes: 0
Reputation: 95578
Android manages Dialog
s for you as an optimization. Unfortunately, it doesn't remove Dialog
s after they have been used. It keeps them around hoping that you will use them again. In general, this isn't an advantage to your application. But that's the way it works.
What you need to do is to remove (delete) your Dialog
s after they have been dismissed. You do this by calling removeDialog()
when you don't need your Dialog
any more.
Upvotes: 0