【问题标题】:out of memory error is raise when i scrolling in gridview当我在gridview中滚动时出现内存不足错误
【发布时间】:2015-03-09 10:21:39
【问题描述】:

当我在完成此任务后将图像放入网格视图时,图像已成功加载到我的网格视图中,但是当我向下滚动时,它会在 logcat 中引发内存不足错误。

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ImageView iv;
    if(convertView==null)
    {
        iv= new ImageView(mcontext);
        WindowManager wm =    (WindowManager)mcontext.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        int height=display.getHeight()/2;
        int width=display.getWidth()/2;
        iv.setLayoutParams(new GridView.LayoutParams(width,width));
        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
    }
    byte[] stringimage = Base64.decode(images.get(position),Base64.DEFAULT);
    iv.setImageBitmap(BitmapFactory.decodeByteArray(stringimage,0,stringimage.length));
    return iv;
}

【问题讨论】:

  • 顺便说一句,您不必在每次迭代中都进行显示宽度/高度计算。在构造函数中的某个地方就足够了。图像阵列的大小是多少?您要加载多大的图像?您可能应该在加载图像视图之前包含一些缩放
  • 您应该对位图使用 SoftReference,例如:link

标签: android gridview imageview


【解决方案1】:

嗯,问题正是您所期望的。 Android 会为您的程序分配一些内存。当您滚动浏览网格时,您可能需要更多空间来存储新图像。如果您的图像太大,您可能会耗尽内存。

在将整个内容加载到内存之前尝试减小位图的大小。

您可以使用BitmapFactory.Options 请求不使用inJustDecodeBounds 将图像加载到内存中。这将告诉您图像有多大,您可以随意缩放。

类似这样的:

    BitmapFactory.Options options = new BitmapFactory.Options();

    //inJustDecodeBounds as true ensures bitmap is not loaded into memory
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(somePath, options);
    int width= options.outWidth;
    int height= options.outHeight;

现在你有了高度和宽度,并且可以尝试确定图像对于它的 imageview 是否太大。请记住,虽然用相机拍摄的照片可能是 1920x1080 像素,但您的图像视图可能只显示 200x100 像素或其他东西。没有理由加载所有像素。

【讨论】:

  • 但是你能给我一些其他的选择来将图像存储在缓存中吗?因为当我将图像设置为位图时我看到日志猫然后堆大小增加所以我为什么要使用缓存选项
猜你喜欢
  • 2017-05-13
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-10
相关资源
最近更新 更多