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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With