使用Universal Image Loader在GridView中加载图像

时间:2013-09-12 12:51:32

标签: android android-imageview android-view android-gridview universal-image-loader

我正在使用Universal Image Loader 1.8.6库来加载从网络上拍摄的动态图像。

ImageLoaderConfiguration配置如下:

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
    .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
    .threadPoolSize(3) // default
    .threadPriority(Thread.NORM_PRIORITY - 1) // default
    .denyCacheImageMultipleSizesInMemory()
    .memoryCacheSize(2 * 1024 * 1024)
    .memoryCacheSizePercentage(13) // default
    .discCacheSize(50 * 1024 * 1024)
    .discCacheFileCount(100)
    .imageDownloader(new BaseImageDownloader(getApplicationContext())) // default
    .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
    .writeDebugLogs()
    .build();

DisplayImageOptions配置为:

DisplayImageOptions options = new DisplayImageOptions.Builder()
    .showStubImage(R.drawable.no_foto)
    .showImageForEmptyUri(R.drawable.no_foto)
    .showImageOnFail(R.drawable.no_foto)
    .build();

我的ArrayAdapter中的方法getView包含代码:

iv.setImageResource(R.drawable.no_foto); 
imageLoader.displayImage(basePath+immagine, iv);

上面代码的第一行用于避免gridView中的视图回收允许将图像设置在错误的位置(直到图片未下载)。

实际问题是:

如果我打开我的活动(包含GridView),由于UIL库,显示的项目可以下载图像。 (同时no_foto.png图像显示在网格的每个视图中)。当所有视图都加载了自己的图像时,如果我尝试向下滚动然后我回来(向上滚动)我必须等待图像重新加载,因为所有视图现在都被no_foto.png图像占用。

如何避免重载这些图像?使用Universal Image Loader,我可以缓存先前加载的图像吗?

注意:由于我的网格可以包含许多图像,因此我将使用disk cache(不是内存缓存)的实现。 我发现.discCacheFileCount()可用于设置缓存文件的最大数量,那么为什么我的文件似乎没有被缓存?

2 个答案:

答案 0 :(得分:10)

我已经解决了问题

我只是宣布选项,但我没有使用它,所以我修改了这一行:

imageLoader.displayImage(basePath+immagine, iv);

成:

imageLoader.displayImage(basePath+immagine, iv, options);

我在选项中添加了方法:

.cacheOnDisc(true)

答案 1 :(得分:7)

默认情况下,UIL中未启用缓存,因此如果要使用缓存,则应使用

// Create default options which will be used for every 
//  displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
    ...
    .cacheInMemory()
    .cacheOnDisc()
    ...
    .build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
    ...
    .defaultDisplayImageOptions(defaultOptions)
    ...
    .build();
ImageLoader.getInstance().init(config); // Do it on Application start

在加载图片时使用:

// Then later, when you want to display image
ImageLoader.getInstance().displayImage(imageUrl, imageView); // Default options will be used

另一种方式是

DisplayImageOptions options = new DisplayImageOptions.Builder()
    ...
    .cacheInMemory()
    .cacheOnDisc()
    ...
    .build();
ImageLoader.getInstance().displayImage(imageUrl, imageView, options); 

您可以找到更多信息here

相关问题