So, I've been looking at the ImageView source for a while, but I haven't figured out a hook to do this yet.
The problem: having, let's say, 30 400x800 images inside a ScrollView (the number of images is variable). Since they fit exactly in the screen they will take 1.3 MB of RAM each.
What I want: to be able to load/unload bitmaps for the ImageViews that are currently visible inside a ScrollView. If the user scrolls and the bitmap is no longer visible (within a distance threshold) the bitmap should be recycled so that the memory can be used by other bitmaps in the same ScrollView. I'm doing downsampling and all that, so no worries there. Bonus points if you do this by only extending ImageView (I would like to not mess with the ScrollView if possible).
Summary: I can make the images load only after the ImageView becomes visible (using a clever trick), but I don't know when to unload them.
Notes: I can't do this with a ListView due to other usability reasons.
Call this method when you want to recycle your bitmaps.
public static void recycleImagesFromView(View view) {
if(view instanceof ImageView)
{
Drawable drawable = ((ImageView)view).getDrawable();
if(drawable instanceof BitmapDrawable)
{
BitmapDrawable bitmapDrawable = (BitmapDrawable)drawable;
bitmapDrawable.getBitmap().recycle();
}
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
recycleImagesFromView(((ViewGroup) view).getChildAt(i));
}
}
}
Have a look at the android documentation about "How to draw bitmaps" Also the code example called bitmap fun.
If you use a ListView or a GridView the ImageView objects are getting recycled and the actual bitmap gets released to be cleaned up by the GC.
You also want to resize the original images to the screen size and cache them on disk and/or RAM. This will safe you a lot of space and the actual size should get down to a couple of hundert KB. You can also try to display the images in half the resolution of your display. The result should still be good while using much less RAM.
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