ImageView:如果 ImageView 不可见(在 ScrollView 内),则自动回收位图 [英] ImageView: automatically recycle bitmap if ImageView is not visible (within ScrollView)

查看:27
本文介绍了ImageView:如果 ImageView 不可见(在 ScrollView 内),则自动回收位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我一直在查看 ImageView 源代码,但我还没有想出一个钩子来做这件事.

So, I've been looking at the ImageView source for a while, but I haven't figured out a hook to do this yet.

问题:比方说,在一个 ScrollView 中有 30 个 400x800 的图像(图像的数量是可变的).由于它们完全适合屏幕,因此它们每个将占用 1.3 MB 的 RAM.

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.

我想要的是:能够加载/卸载当前在 ScrollView 中可见的 ImageView 的位图.如果用户滚动并且位图不再可见(在距离阈值内),则应回收位图,以便同一 ScrollView 中的其他位图可以使用内存.我正在做下采样和所有这些,所以不用担心.如果您仅通过扩展 ImageView 来执行此操作,则可以加分(如果可能的话,我不想弄乱 ScrollView).

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).

总结:我只能在 ImageView 变得可见后才加载图像(使用一个聪明的技巧),但我不知道何时卸载它们.

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.

注意:由于其他可用性原因,我无法使用 ListView 执行此操作.

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));
                }
            }
        }

这篇关于ImageView:如果 ImageView 不可见(在 ScrollView 内),则自动回收位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆