Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destroy a drawable inside an ImageView if we don't need it?

This question is related with Do we have to explicitly recycle the bitmap if we don't need it?.

There is an ImageView have a drawable, when user clicks a button, it will assign a new drawable to the ImageView.

Do we have to destroy the old drawable belongs to the ImageView, and how?

Drawable oriDrawable = imageView.getDrawable()

// set callback to null
oriDrawable.setCallback(null);

// get the bitmap and recycle it
((BitmapDrawable)oriDrawable).getBitmap().recycle();

Is the code above correct? What's the best solution?

like image 545
Freewind Avatar asked Sep 21 '12 16:09

Freewind


2 Answers

You could try using something like:

Drawable drawable = imageView.getDrawable();
if (drawable instanceof BitmapDrawable) {
    BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
    Bitmap bitmap = bitmapDrawable.getBitmap();
    bitmap.recycle();
}

Where imageView is your ImageView.

Original answer here.

like image 104
Raghav Sood Avatar answered Nov 07 '22 19:11

Raghav Sood


Is this just a general question or are you running out of memory? I would not make this optimisation until you really have a problem.

In general if you are loading bitmaps from drawable folders that are not large (large as in megabytes) then you should not really run into a problem.

First you need to make sure the assets you are loading are optimal for where you display them, for example there is no point in setting an ImageView to an image thats 1024 x 1024 in size if the area you display the image is a size of 64x64.

Breaking the bitmap budget is usually caused by loading in images of an unknown size or just simply getting the image sizes wrong as described above, swapping an ImageView frequently will generally not give you an issue with optimal sized images.

There is a great article in Android Training that covers loading bitmaps optimally http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

Hope that helps

like image 4
Ian Warwick Avatar answered Nov 07 '22 20:11

Ian Warwick