【问题标题】:Android OutOfMemoryException while changing ImageView Resource更改 ImageView 资源时出现 Android OutOfMemoryException
【发布时间】:2013-12-21 00:37:16
【问题描述】:

在我的应用程序中,我使用此方法多次更改 ImageView 的资源:

private void setIcon(int id, int imageSource) {
    ((ImageView)findViewById(id)).setBackgroundResource(imageSource);
}

过了一会儿,我得到了 OutOfMemoryException。在我加载新资源(图像)之前,有没有更好的方法来释放旧资源(图像)?

编辑

private void setIcon(int id, int imageSource) {
    ImageView imageView = (ImageView)findViewById(id);
    Drawable bg= imageView.getBackground();

    if(bg != null && bg instanceof BitmapDrawable) {
         BitmapDrawable bitmapDrawable = (BitmapDrawable) bg;
         bitmapDrawable.getBitmap().recycle();
         if(D)Log.d(TAG, "recycled bitmap");
    }

    Bitmap bm = BitmapFactory.decodeResource(getResources(), imageSource);
    imageView.setImageBitmap(bm);

}

【问题讨论】:

标签: android exception resources imageview out-of-memory


【解决方案1】:

在设置新背景之前,请尝试为旧背景清除内存,如下所示:

Drawable bg = image.getBackground();
if(bg != null && bg instanceof BitmapDrawable) {
    BitmapDrawable bitmapDrawable = (BitmapDrawable) bg;
    bitmapDrawable.getBitmap().recycle();
}

您有设置背景资源的具体原因吗?你不能简单地使用 image.setResource()。这样更容易获取位图并循环使用。

编辑:如果您只想要一张图像(没有叠加层或其他东西),那么这更容易(以及它应该如何):

ImageView image = (ImageView)findViewById(id);
image.setImageResource(imageSource);

使用位图:

Bitmap bm = BitmapFactory.decodeResource(getResources(), id);
image.setImageBitmap(bm);
image.getDrawable(); // will return a BitmapDrawable

【讨论】:

  • 如何从 R.drawable.image 构建 BitmapDrawable ??
  • 用 BitmapDrawable 示例更新了我的答案。
  • 我编辑了我的帖子。但我得到 OutOfMemoryExc 比以前更快。我从不输入块来记录位图。它是怎么来的?
猜你喜欢
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 2011-02-27
  • 2011-11-01
  • 2013-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多