【发布时间】:2015-03-08 20:46:07
【问题描述】:
看来,当我为 ImageView 调用 setImageDrawable(null) 时,位图没有被释放。我该怎么做才能强制它释放位图内存?
我有一个需要显示大量可绘制对象的活动,但不能同时显示。我已经扩展了 ImageView,如下所示。 XML 布局文件声明了它的实例,“src”属性设置为“@null”。作为替代,我有一个自定义属性来保存可绘制资源 ID。
public class ImageViewHolder extends ImageView
{
int srcId = 0;
//-----------------------------------------------------------------------------
public ImageViewHolder (Context context, AttributeSet attrs)
{
super (context, attrs);
TypedArray a = context.obtainStyledAttributes (attrs, R.styleable.ImageViewHolder, 0, 0);
srcId = a.getResourceId (R.styleable.ImageViewHolder_src, 0);
a.recycle();
}
//-----------------------------------------------------------------------------
public void showDrawable (boolean makeVisible)
{
if (makeVisible)
{
// Drawable d = getResources().getDrawable (srcId);
// setImageDrawable (d);
setImageResource (srcId);
}
else // hide & free memory
{
Bitmap bitmap = ((BitmapDrawable)getDrawable()).getBitmap();
setImageResource(0);
bitmap.recycle();
// setImageDrawable (null);
}
}
}
我尝试使用 SetImagerResource() 代替但得到相同的结果。我还尝试在清除可绘制对象后调用 System.gc(),这只会推迟我的设备内存不足的时间点。
有什么想法吗?
【问题讨论】:
-
你可以仔细试试Bitmap.recycle()
-
好主意。没用 - 仍然出现内存不足错误。
-
位图有多大?你在记忆中保留了多少?你在使用运行时缓存吗?
-
在我目前正在测试的特定设备上,它们大约为 600x800 像素。我认为最大的情况是一次显示 3 个。其余的都应该被释放,使用我帖子中的代码。我没有对这些位图进行任何缓存 - 我正在添加 ImagveView 扩展的其余部分供您查看。
-
600*800 没什么大不了的。每张位图 1.8 兆字节...当然你还要考虑屏幕的密度
标签: android memory-leaks imageview