Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

由淺入深:Android ListView 性能優化的完整實戰

編輯:關於 Android 程式設計

ListView 是一種可以顯示一系列項目並能進行滾動顯示的 View。在每一行裡,既可以是簡單的文本,也可以是複雜的結構。一般情況下,我們都需要保證 ListView 運行良好——渲染更快、滾動流暢。本文就 ListView 的使用,提供幾種解決不同性能問題的方案。

Adapter 基礎

使用 ListView 就不得不使用 ListAdapter 來顯示內容。SDK 中已經有幾種簡單實現的 Adapter:

  • ArrayAdapter<T>(顯示數組對象,使用 toString() 來顯示)
  • SimpleAdapter(顯示 Maps 列表)
  • SimpleCursorAdapter(顯示通過 Cursor 從 DB 中獲取的數據)

這些實現對於顯示簡單列表來說非常棒。一旦列表比較複雜,你就不得不自己編寫 ListAdapter。多數情況下,直接從 ArrayAdapter 擴展就能很好地處理一組對象,此時你需要做的只是告訴系統如何處理列表中的對象,通過重寫 getView(int, View, ViewGroup) 方法即可達到。

示例:圖文列表

舉一個需要自定義 ListAdapter 的例子:顯示一組圖片,圖片旁邊挨著文字,且圖片需要實時從網絡下載。先創建一個類來代表列表中的項目:

public class ImageAndText {
    private String imageUrl;
    private String text;

    public ImageAndText(String imageUrl, String text) {
        this.imageUrl = imageUrl;
        this.text = text;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public String getText() {
        return text;
    }
}

接下來實現一個 ListAdapter 來顯示 ImageAndText 列表:

public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> {

    public ImageAndTextListAdapter(Activity activity, List<ImageAndText> imageAndTexts) {
        super(activity, 0, imageAndTexts);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Activity activity = (Activity) getContext();
        LayoutInflater inflater = activity.getLayoutInflater();

        // Inflate the views from XML
        View rowView = inflater.inflate(R.layout.image_and_text_row, null);
        ImageAndText imageAndText = getItem(position);

        // Load the image and set it on the ImageView
        ImageView imageView = (ImageView) rowView.findViewById(R.id.image);
        imageView.setImageDrawable(loadImageFromUrl(imageAndText.getImageUrl()));

        // Set the text on the TextView
        TextView textView = (TextView) rowView.findViewById(R.id.text);
        textView.setText(imageAndText.getText());

        return rowView;
    }

    public static Drawable loadImageFromUrl(String url) {
        InputStream inputStream;
        try {
            inputStream = new URL(url).openStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Drawable.createFromStream(inputStream, "src");
    }
}

這些 View 都是從 "image_and_text_row.xml" 中 inflate 的:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/default_image"/>
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

這個 ListAdapter 正如你所期望的那樣,能在 ListView 中加載 ImageAndText。但它唯一適用的場合是那些項目很少、無需滾動即可看到全部的列表。當 ImageAndText 列表內容很多時,你會發現滾動起來一點也不平滑。

性能改善(一):異步加載圖片

上面例子最大的瓶頸是圖片需要從網絡下載。因為我們的代碼都在 UI 線程中執行,所以每當一張圖片從網絡下載時,UI 就會停滯。如果用 3G 網絡代替 WiFi,性能會更糟。

為了解決這個問題,我們想讓圖片下載在單獨的線程裡進行,避免佔用 UI 線程。為此可以使用為這種情況設計的 AsyncTask。不過要注意,AsyncTask 被限制在 10 個以內(這個數量在 Android SDK 中是硬編碼的,無法改變)。當常常有超過 10 個圖片同時下載時,這就成了一個限制。

AsyncImageLoader:線程 + Handler + 緩存

一個變通的做法是手動為每個圖片創建一個線程,並用 Handler 將下載的圖片 invoke 回 UI 線程——因為我們只能在 UI 線程中修改 UI。下面這個 AsyncImageLoader 類利用線程和 Handler 負責圖片下載,同時緩存圖片,防止單個圖片被重複下載:

public class AsyncImageLoader {
    private HashMap<String, SoftReference<Drawable>> imageCache;

    public AsyncImageLoader() {
        imageCache = new HashMap<String, SoftReference<Drawable>>();
    }

    public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
        if (imageCache.containsKey(imageUrl)) {
            SoftReference<Drawable> softReference = imageCache.get(imageUrl);
            Drawable drawable = softReference.get();
            if (drawable != null) {
                return drawable;
            }
        }
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message message) {
                imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
            }
        };
        new Thread() {
            @Override
            public void run() {
                Drawable drawable = loadImageFromUrl(imageUrl);
                imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                Message message = handler.obtainMessage(0, drawable);
                handler.sendMessage(message);
            }
        }.start();
        return null;
    }

    public static Drawable loadImageFromUrl(String url) {
        // ...
    }

    public interface ImageCallback {
        public void imageLoaded(Drawable imageDrawable, String imageUrl);
    }
}

這裡使用了 SoftReference 來緩存圖片,允許 GC 在需要時清理緩存中的圖片。它的工作方式如下:

  • 調用 loadDrawable(ImageUrl, imageCallback),傳入一個匿名實現的 ImageCallback 接口。
  • 如果圖片不在緩存中,就從單獨的線程下載,並在下載結束時通過 ImageCallback 回調。
  • 如果圖片確實存在於緩存中,就馬上返回,不回調 ImageCallback。

注意:程序中只能存在一個 AsyncImageLoader 實例,否則緩存無法正常工作。在 ImageAndTextListAdapter 中可以這樣替換原來的加載邏輯:

final ImageView imageView = (ImageView) rowView.findViewById(R.id.image);
Drawable cachedImage = asyncImageLoader.loadDrawable(imageAndText.getImageUrl(),
        new ImageCallback() {
            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
                imageView.setImageDrawable(imageDrawable);
            }
        });
imageView.setImageDrawable(cachedImage);

使用這個方法後,ListView 執行得很好了,滑動也更平滑了,因為 UI 線程再也不會被圖片加載阻塞。

性能改善(二):視圖重用與緩存

如果你嘗試了上面的方案,會發現 ListView 還不是 100% 平滑,仍有東西阻礙著它的流暢性。這裡還有兩個可以改進的地方:

  • findViewById() 的昂貴調用。
  • 每次都重新 inflate XML。

因此修改代碼如下,引入 convertView 重用和 ViewCache 緩存:

public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> {

    private ListView listView;
    private AsyncImageLoader asyncImageLoader;

    public ImageAndTextListAdapter(Activity activity, List<ImageAndText> imageAndTexts, ListView listView) {
        super(activity, 0, imageAndTexts);
        this.listView = listView;
        asyncImageLoader = new AsyncImageLoader();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Activity activity = (Activity) getContext();

        // Inflate the views from XML
        View rowView = convertView;
        ViewCache viewCache;
        if (rowView == null) {
            LayoutInflater inflater = activity.getLayoutInflater();
            rowView = inflater.inflate(R.layout.image_and_text_row, null);
            viewCache = new ViewCache(rowView);
            rowView.setTag(viewCache);
        } else {
            viewCache = (ViewCache) rowView.getTag();
        }

        ImageAndText imageAndText = getItem(position);

        // Load the image and set it on the ImageView
        String imageUrl = imageAndText.getImageUrl();
        ImageView imageView = viewCache.getImageView();
        imageView.setTag(imageUrl);
        Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl,
                new ImageCallback() {
                    public void imageLoaded(Drawable imageDrawable, String imageUrl) {
                        ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
                        if (imageViewByTag != null) {
                            imageViewByTag.setImageDrawable(imageDrawable);
                        }
                    }
                });
        imageView.setImageDrawable(cachedImage);

        // Set the text on the TextView
        TextView textView = viewCache.getTextView();
        textView.setText(imageAndText.getText());

        return rowView;
    }
}

這裡有兩點需要注意:第一,drawable 不再是加載完畢後直接設置到 ImageView 上,而是通過 tag 查找正確的 ImageView。這是因為我們現在重用了 View,圖片有可能出現在錯誤的行上,所以我們需要持有 ListView 的引用來通過 tag 查找 ImageView。

第二,我們使用了一個叫 ViewCache 的對象,它這樣定義:

public class ViewCache {
    private View baseView;
    private TextView textView;
    private ImageView imageView;

    public ViewCache(View baseView) {
        this.baseView = baseView;
    }

    public TextView getTextView() {
        if (textView == null) {
            textView = (TextView) baseView.findViewById(R.id.text);
        }
        return textView;
    }

    public ImageView getImageView() {
        if (imageView == null) {
            imageView = (ImageView) baseView.findViewById(R.id.image);
        }
        return imageView;
    }
}

有了 ViewCache 對象,我們就不再需要反覆調用 findViewById() 來查詢 View 對象了。

總結

本文演示了三種改進 ListView 性能的方法:

  • 在單獨的線程裡加載圖片。
  • 重用列表中的行(convertView)。
  • 緩存行中的 View(ViewCache)。

這三招相互配合,能讓你的 ListView 即使在處理大量圖文混排數據時,也能保持絲滑的滾動體驗。

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