Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

ListView 效能優化實戰:異步載入圖片打造順暢滑動體驗

編輯:Android 開發實例

ListView 是 Android 中最常見的捲動式檢視元件之一,它能夠將大量資料項目以列表形式呈現,並支援上下滑動瀏覽。然而,當每一列的 Item 結構較為複雜,例如需要從網路下載圖示或縮圖時,問題就浮現了:以目前一般使用者家中的網路頻寬而言,若採用同步方式載入,幾乎不可能維持 ListView 的順暢滑動,畫面往往會出現明顯的卡頓。

要解決這個痛點,核心思路很簡單——把圖片的抓取與解碼工作交給多執行緒處理,改採異步載入的方式,讓主執行緒(UI 執行緒)不必為了等待網路回應而被阻塞。

以下先來看負責異步載入的 AsyncImageLoader 類別:

  1. public class AsyncImageLoader {  
  2.     private HashMap<String, SoftReference<Drawable>> imageCache;  
  3.    
  4.     public AsyncImageLoader() {  
  5.         imageCache = new HashMap<String, SoftReference<Drawable>>();  
  6.     }  
  7.    
  8.     public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {  
  9.         if (imageCache.containsKey(imageUrl)) {  
  10.             SoftReference<Drawable> softReference = imageCache.get(imageUrl);  
  11.             Drawable drawable = softReference.get();  
  12.             if (drawable != null) {  
  13.                 return drawable;  
  14.             }  
  15.         }  
  16.         final Handler handler = new Handler() {  
  17.             @Override 
  18.             public void handleMessage(Message message) {  
  19.                 imageCallback.imageLoaded((Drawable) message.obj, imageUrl);  
  20.             }  
  21.         };  
  22.         new Thread() {  
  23.             @Override 
  24.             public void run() {  
  25.                 Drawable drawable = loadImageFromUrl(imageUrl);  
  26.                 imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));  
  27.                 Message message = handler.obtainMessage(0, drawable);  
  28.                 handler.sendMessage(message);  
  29.             }  
  30.         }.start();  
  31.         return null;  
  32.     }  
  33.    
  34.     public static Drawable loadImageFromUrl(String url) {  
  35.         // ...  
  36.     }  
  37.    
  38.     public interface ImageCallback {  
  39.         public void imageLoaded(Drawable imageDrawable, String imageUrl);  
  40.     }  
  41. }  

這段程式碼有幾個值得留意的細節。首先,它以 SoftReference(軟引用)來快取圖片,這樣做的優點是:當系統記憶體吃緊時,垃圾回收機制(GC)能夠在必要的時候自動回收這些快取的圖片物件,避免記憶體溢出。

它的運作流程大致如下:

  • 呼叫 loadDrawable(ImageUrl, imageCallback),並傳入一個匿名實作的 ImageCallback 介面。
  • 若圖片尚未存在於快取中,則會在獨立的執行緒裡下載,下載完成後透過 ImageCallback 回呼通知。
  • 若圖片已存在於快取中,則立即回傳,不會觸發 ImageCallback 回呼。

接著,我們還可以參考 2009 年 Google I/O 開發者大會上提到的技巧,進一步優化 Adapter。做法是引入 ViewHolder 模式,藉此減少 inflate XML 版面配置以及 findViewById() 這類較耗時的操作。

  1. public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> {  
  2.    
  3.     private ListView listView;  
  4.     private AsyncImageLoader asyncImageLoader;  
  5.    
  6.     public ImageAndTextListAdapter(Activity activity, List<ImageAndText> imageAndTexts, ListView listView) {  
  7.         super(activity, 0, imageAndTexts);  
  8.         this.listView = listView;  
  9.         asyncImageLoader = new AsyncImageLoader();  
  10.     }  
  11.    
  12.     @Override 
  13.     public View getView(int position, View convertView, ViewGroup parent) {  
  14.         Activity activity = (Activity) getContext();  
  15.    
  16.         //Inflate the views from XML  
  17.         View rowView = convertView;  
  18.         ViewCache viewCache;  
  19.         if (rowView == null) {  
  20.             LayoutInflater inflater = activity.getLayoutInflater();  
  21.             rowView = inflater.inflate(R.layout.image_and_text_row, null);  
  22.             viewCache = new ViewCache(rowView);  
  23.             rowView.setTag(viewCache);  
  24.             } else {  
  25.             viewCache = (ViewCache) rowView.getTag();  
  26.             }  
  27.             ImageAndText imageAndText = getItem(position);  
  28.    
  29.         //Load the image and set it on the ImageView  
  30.         String imageUrl = imageAndText.getImageUrl();  
  31.         ImageView imageView = viewCache.getImageView();  
  32.         imageView.setTag(imageUrl);  
  33.         Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl, new ImageCallback() {  
  34.             public void imageLoaded(Drawable imageDrawable, String imageUrl) {  
  35.                 ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);  
  36.                 if (imageViewByTag != null) {  
  37.                     imageViewByTag.setImageDrawable(imageDrawable);  
  38.                     }  
  39.                 }  
  40.             });  
  41.             imageView.setImageDrawable(cachedImage);  
  42.    
  43.         //Set the text on the TextView  
  44.         TextView textView = viewCache.getTextView();  
  45.         textView.setText(imageAndText.getText());  
  46.    
  47.         return rowView;  
  48.     }  
  49. }

請特別留意這裡的處理方式:圖片下載完成後,並不是直接把 Drawable 設定到原本的 ImageView 上,而是透過 Tag 去反查對應的元件。之所以要這樣做,是因為 ListView 中的 View 會被反覆重用(recycle),若不透過 Tag 定位,很可能把圖片錯誤地設定到已經被回收重用的其他列上。由於我們持有 listView 的參考,因此可以藉由 Tag 精準找到目標元件,具體實作如下:

  1. ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);  
  2.                 if (imageViewByTag != null) {  
  3.                     imageViewByTag.setImageDrawable(imageDrawable);  
  4.                 }

而 ViewCache 則用來快取列中的各個子檢視,大幅減少 findViewById 的呼叫次數:

  1. public class ViewCache {  
  2.    
  3.     private View baseView;  
  4.     private TextView textView;  
  5.     private ImageView imageView;  
  6.    
  7.     public ViewCache(View baseView) {  
  8.         this.baseView = baseView;  
  9.     }  
  10.    
  11.     public TextView getTextView() {  
  12.         if (textView == null) {  
  13.             textView = (TextView) baseView.findViewById(R.id.text);  
  14.         }  
  15.         return textView;  
  16.     }  
  17.    
  18.     public ImageView getImageView() {  
  19.         if (imageView == null) {  
  20.             imageView = (ImageView) baseView.findViewById(R.id.image);  
  21.         }  
  22.         return imageView;  
  23.     }  
  24. }

總結

整篇文章的核心,其實就三個關鍵的優化手段:

  • 在單一背景執行緒中載入圖片,避免阻塞 UI 執行緒。
  • 重用列表中的列(convertView),不再重複 inflate。
  • 快取列內的 View 元件,減少 findViewById 的呼叫開銷。

把這三點搭配起來,即便每列都藏著需要從網路抓取的圖示,ListView 依然能維持如絲般順滑的捲動體驗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved