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

守給你的承諾、 提交于 2019-12-03 12:43:43

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.

What you really want is to use an ArrayAdapter for this. If, like your notes suggest, that is not possible (although i don't see why) take a look at the source for array adapter and rewrite one to your own needs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!