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

universal-image-loader 入門:在 GridView 中異步載入網路圖片

編輯:關於 Android 開發

universal-image-loader 入門:在 GridView 中異步載入網路圖片

本文示範如何從接口拉取資料,並用 universal-image-loader 把商品圖片呈現在自訂的 GridView 上。下圖為效果參考:

實作步驟如下:

1、先定義版面配置,這裡用自訂的 MyGridView 來展示商品。

2、匯入 jar 套件 universal-image-loader-1.8.6-with-sources。使用 ImageLoader 前務必先初始化:

ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));

否則會拋出 java.lang.IllegalStateException: ImageLoader must be init with configuration before using,意思就是使用前必須先初始化。

3、定義 Adapter 在 getView 中展示商品。作者實作時發現第一筆資料總會重複請求,加載慢又耗伺服器資源,於是定義一個 View 陣列暫存已建立的 View,有資料時就不再重複請求(這種做法局限性較大,僅供參考)。

4、開啟子執行緒在背景加載資料,於 Handler 中解析資料並更新界面。

主要程式碼如下。

自訂 GridView(重寫 onMeasure 讓它能完整顯示於 ScrollView 中):

package com.demo.content;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;

public class MyGridView extends GridView {
    public MyGridView(Context context, AttributeSet attrs) { super(context, attrs); }
    public MyGridView(Context context) { super(context); }
    public MyGridView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); }
    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}

版面配置:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#eee"
            android:orientation="vertical" >
            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/app_name"
                android:textColor="#000" />
            <View
                android:layout_width="match_parent"
                android:layout_height="5dp"
                android:background="@drawable/btn_normal" />
            <com.demo.content.MyGridView
                android:id="@+id/gg_mygridview"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:horizontalSpacing="7dp"
                android:numColumns="2"
                android:verticalSpacing="7dp" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

主 Activity:

public class MyMainActivity extends Activity {
    private MyGridView myGridView;
    private DisplayImageOptions options;
    private List<Product> products;
    private String url = "" + "Product/GetProductsByProType/12000000/20";

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.mymainactivity);
        options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.ic_empty)   // 連結為空時
                .showImageOnFail(R.drawable.ic_error)        // 加載失敗
                .resetViewBeforeLoading(true).cacheOnDisc(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .displayer(new FadeInBitmapDisplayer(300))   // 漸現效果
                .build();
        // 建立預設的 ImageLoader 參數,不加會報 IllegalStateException
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));
        myGridView = (MyGridView) findViewById(R.id.gg_mygridview);
        // 開啟子執行緒
        new GetThread(url, handler).start();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case GetThread.SUCCESS:
                    String jsonString = (String) msg.obj;
                    products = getJsonProducts(jsonString);
                    Adapter adapter = new Adapter();
                    myGridView.setAdapter(adapter);
                    break;
            }
        }
    };
}

Adapter 中的 getView 透過 ViewHolder 提升效能,並用 ImageLoader 載入網路圖片:

ImageLoader.getInstance().displayImage(urlString, holder.product_img, options);

背景執行緒 GetThread 用 HttpClient 發送 GET 請求,成功後透過 Handler 把 JSON 字串送回主執行緒解析。

public class GetThread extends Thread {
    public static final int SUCCESS = 10, FAIL = -11;
    private String url;
    private Handler handler;
    public GetThread(String url, Handler handler) {
        this.url = url;
        this.handler = handler;
    }
    @Override
    public void run() {
        super.run();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            Message msg = Message.obtain();
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String jsonString = EntityUtils.toString(httpResponse.getEntity());
                msg.what = SUCCESS;
                msg.obj = jsonString;
                handler.sendMessage(msg);
            } else {
                msg.what = FAIL;
                handler.sendMessage(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

整體流程是:子執行緒拉取 JSON → Handler 解析為 Product 清單 → Adapter 綁定到自訂 GridView → ImageLoader 異步載入並快取圖片,搭配漸現動畫呈現流暢的商品列表。實務上新專案建議改用 Glide 或 Picasso 等維護中的圖片庫,universal-image-loader 已停止更新。

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