android - "Cannot draw recycled bitmaps"在附加到 Adapter 的 Gallery 中显示位图时

标签 android

在 Android 4.1 a 中,对我来说,我们的应用程序中出现了看似奇怪的错误。在应用程序中,扩展 BaseAdapter 的自定义适配器附加到 Gallery 小部件。当从左到右快速滚动时,反之亦然,我得到一个带有异常消息的 FC:

java.lang.IllegalArgumentException: Cannot draw recycled bitmap

getView(..)方法的代码如下:

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

    if (convertView == null){
        // View is not recycled. Inflate the layout.
        LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = vi.inflate(R.layout.gallery_image, parent, false);

        viewHolder = new ViewHolder();
        viewHolder.image = (ImageView) convertView.findViewById(R.id.gallery_image);

        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder)convertView.getTag();
        viewHolder.image.setImageDrawable(null);
    }

    imageLoader.displayImage(images.get(position).getFilename(),
            images.get(position).getUrlThumbnail(),
            viewHolder.image,
            Math.round(BitmapUtil.convertDpToPixel(400f, context)),
            Math.round(BitmapUtil.convertDpToPixel(400f, context)));

    return convertView;
}

我想我应该在某处使 ImageView 无效,但我无法使其正常工作。 ImageLoader 是一个(非常)简单的类,用于加载图像 - 从 LruCache、磁盘/SD 卡或远程获取图像。

最佳答案

您收到此错误是因为您无法访问回收的位图。正如 Android 开发者网站所述:

Free the native object associated with this bitmap, and clear the reference to the pixel data. This will not free the pixel data synchronously; it simply allows it to be garbage collected if there are no other references. The bitmap is marked as "dead", meaning it will throw an exception if getPixels() or setPixels() is called, and will draw nothing. This operation cannot be reversed, so it should only be called if you are sure there are no further uses for the bitmap. This is an advanced call, and normally need not be called, since the normal GC process will free up this memory when there are no more references to this bitmap.

到目前为止,我建议您不要回收 Bitmap,因为它还有用处。因此,请查看您的代码,了解何时调用 recycle() 方法,然后将其删除。

当Bitmap不再需要使用的时候,我建议你使用这种方法来处理Bitmap:

public void disposeBitmap(Bitmap bitmap) {
        bitmap.recycle();
        bitmap = null;
}

希望对您有所帮助。

关于android - "Cannot draw recycled bitmaps"在附加到 Adapter 的 Gallery 中显示位图时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12218976/

相关文章:

Android,即使在静音状态下手机也会播放通知声音?我应该检查静音模式吗?

android - 我的android简单计算器应用有什么问题?

javascript - 尝试在 android webview 应用程序中进行 facebook 登录时出现空白页面

java - 解压缩过程使设备无响应

android - 如何使用一些预定义的文本和图像打开 Facebook Write Post

android - Activity fragment

Android 2.2 Spinner 在 Actionbar 中看起来很旧

java - 方向更改在 fragment 中获得相同的布局

java - 按下按钮后 Android 模拟器屏幕变为空白

android - Admob 帐户在尝试展示我的第一个真实广告后被禁用