2013-04-08 97 views
1

我有一个列表视图,其中图像从互联网加载,然后缓存在磁盘上。虽然滚动,我试图加载使用的ExecutorService在后台线程从磁盘映像(自会有多个图像,同时滚动) - 是这样的:从后台加载缓存的图像在后台线程android

executorService.submit(new Runnable() { 
    @Override 
    public void run() { 
      // load images from the disk 
      // reconnect with UI thread using handler 
     } 
} 

然而,滚动一点也不顺利并且非常生涩 - 就好像UI线程在某处被阻塞一样。但是当我评论这个给定的代码时,那么滚动是平滑的。我无法理解我的实施中的缺陷。

编辑:刚才我发现,当我将消息从后台线程传递给UI线程时,问题正在发生。如果我评论的部分,滚动平滑(但ofcourse不显示图像)

+3

您可以尝试LazyList => https://github.com/thest1/LazyList – 2013-04-08 10:15:19

+0

感谢Paresh,但我已经完成了我的实现,只有这个提到的问题。如果我能知道我的代码中的错误,那将会非常有帮助。 – 2013-04-08 10:24:32

+0

这是你做得很好的工作。 – 2013-04-08 10:26:31

回答

1

您可以使用延迟加载或通用图像装载机

懒列表是从SD卡或FOMR使用服务器的URL的图像延迟加载。这就像按需加载图像。

图像可以缓存到本地SD卡或手机mmeory。网址被认为是关键。如果密钥存在于sdcard中,则显示来自SD卡的图像,否则通过从服务器下载显示图像并将其缓存到您选择的位置。缓存限制可以设置。您也可以选择自己的位置来缓存图像。缓存也可以被清除。

而不是用户等待下载大图像,然后显示懒惰列表按需加载图像。由于缓存的图像区域可以离线显示图像。

https://github.com/thest1/LazyList。懒列表

在你getview

imageLoader.DisplayImage(imageurl, imageview); ImageLoader Display method 

public void DisplayImage(String url, ImageView imageView) //url and imageview as parameters 
{ 
imageViews.put(imageView, url); 
Bitmap bitmap=memoryCache.get(url); //get image from cache using url as key 
if(bitmap!=null)   //if image exists 
imageView.setImageBitmap(bitmap); //dispaly iamge 
else //downlaod image and dispaly. add to cache. 
{ 
queuePhoto(url, imageView); 
imageView.setImageResource(stub_id); 
} 
} 

懒列表的替代方案是通用图像装载机

https://github.com/nostra13/Android-Universal-Image-Loader

它基于Lazy List(基于相同原理)。但它有很多其他配置。我宁愿使用通用图像加载程序,因为它提供了更多的配置选项。如果downlaod失败,您可以显示错误图像。可以显示圆角的图像。可以缓存在光盘或内存上。可以压缩图像。

在您的自定义适配器构造

File cacheDir = StorageUtils.getOwnCacheDirectory(a, "your folder"); 

// Get singletone instance of ImageLoader 
imageLoader = ImageLoader.getInstance(); 
// Create configuration for ImageLoader (all options are optional) 
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a) 
    // You can pass your own memory cache implementation 
.discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation 
.discCacheFileNameGenerator(new HashCodeFileNameGenerator()) 
.enableLogging() 
.build(); 
// Initialize ImageLoader with created configuration. Do it once. 
imageLoader.init(config); 
options = new DisplayImageOptions.Builder() 
.showStubImage(R.drawable.stub_id)//display stub image 
.cacheInMemory() 
.cacheOnDisc() 
.displayer(new RoundedBitmapDisplayer(20)) 
.build(); 

在你getView()

ImageView image=(ImageView)vi.findViewById(R.id.imageview); 
imageLoader.displayImage(imageurl, image,options);//provide imageurl, imageview and options 

你可以用其他选项配置,以满足您的需求。

随着延迟加载/通用图像加载器,您可以查看持有人顺利滚动和性能

http://developer.android.com/training/improving-layouts/smooth-scrolling.html