ImageView: automatically recycle bitmap if ImageView is not visible (within ScrollView)(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 内),则自动回收位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ImageView:如果 ImageView 不可见(在 ScrollView 内),则自动回收位图
基础教程推荐
- Android:对话框关闭而不调用关闭 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01