如何在gridview中有效加载互联网图像?

2024-03-06

我使用以下示例在我的活动中显示互联网图像。

http://developer.android.com/resources/tutorials/views/hello-gridview.html http://developer.android.com/resources/tutorials/views/hello-gridview.html

在自定义图像适配器中,我直接从互联网加载图像并将其分配给 imageview。

它在 gridview 中显示图像,一切正常,但这不是有效的方法。

当我滚动 gridview 时,它会一次又一次地加载图像,这就是 gridview 滚动非常慢的原因

是否有缓存或一些有用的技术可以使其更快?


创建一个返回位图的全局静态方法。该方法将采用参数:context,imageUrl, and imageName.

在方法中:

  1. 检查缓存中是否已存在该文件。如果是,则返回位图

        if(new File(context.getCacheDir(), imageName).exists())
            return BitmapFactory.decodeFile(new File(context.getCacheDir(), imageName).getPath());
    
  2. 否则,您必须从网络加载图像,并将其保存到缓存中:

    image = BitmapFactory.decodeStream(HttpClient.fetchInputStream(imageUrl));
    
    
    
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(new File(context.getCacheDir(), imageName));
    }
    
    
    //this should never happen
    catch(FileNotFoundException e) {
        if(Constants.LOGGING)
            Log.e(TAG, e.toString(), e);
    }
    
    
    //if the file couldn't be saved
    if(!image.compress(Bitmap.CompressFormat.JPEG, 100, fos)) {
        Log.e(TAG, "The image could not be saved: " + imageName + " - " + imageUrl);
        image = BitmapFactory.decodeResource(context.getResources(), R.drawable.default_cached_image);
    }
    fos.flush();
    fos.close();
    
    
    return image;
    

预载一个Vector<SoftReference<Bitmap>>使用上面的方法创建具有所有位图的对象AsyncTask类,还有另一个类List拿着一个MapimageUrls 和 imageNames(以便以后需要重新加载图像时访问),然后设置GridView适配器。

我建议使用数组SoftReferences以减少内存使用量。如果您有大量位图,您可能会遇到内存问题。

所以在你的getView方法,你可能有类似的东西(其中icons is a Vector持有型SoftReference<Bitmap>:

myImageView.setImageBitmap(icons.get(position).get());

你需要做一个检查:

if(icons.get(position).get() == null) {
    myImageView.setImageBitmap(defaultBitmap);
    new ReloadImageTask(context).execute(position);
}

in the ReloadImageTask AsyncTask类,只需使用正确的参数调用上面创建的全局方法,然后notifyDataSetChanged in onPostExecute

可能需要完成一些额外的工作,以确保当 AsyncTask 已经针对特定项目运行时,您不会启动它

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在gridview中有效加载互联网图像? 的相关文章

随机推荐