【问题标题】:ImageView.setImageDrawable(null) not freeing memoryImageView.setImageDrawable(null) 不释放内存
【发布时间】: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


【解决方案1】:

而不是使用

setImageResource (srcId);

使用

Resources r = getResources();
Bitmap b = BitmapFactory.decodeResource (r, srcId);
setImageBitmap (b);

这会绕过 Resources() 缓存,并在每次需要时重新创建位图。在测试了这段代码之后,我最终仍然会遇到内存不足的错误,但要花更长的时间才能到达那里。我会假设它是由其他原因引起的。现在,花在这个问题上的时间已经足够了:)

【讨论】:

    猜你喜欢
    • 2012-07-08
    • 1970-01-01
    • 2017-06-29
    • 2011-06-30
    • 2016-09-14
    • 2015-08-19
    • 2012-05-15
    • 2018-01-26
    • 2011-09-30
    相关资源
    最近更新 更多