2013-04-08 90 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