Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageView: automatically recycle bitmap if ImageView is not visible (within ScrollView)

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.

like image 352
dmon Avatar asked Dec 01 '11 23:12

dmon


2 Answers

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));
                }
            }
        }
like image 174
Pawan Maheshwari Avatar answered Sep 28 '22 02:09

Pawan Maheshwari


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.

like image 30
philipp Avatar answered Sep 28 '22 04:09

philipp