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

Freewind picture Freewind · Sep 21, 2012 · Viewed 14.4k times · Source

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?

Answer

Raghav Sood picture Raghav Sood · Sep 21, 2012

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.