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

Android 學習筆記:Adapter 是什麼

編輯:關於 Android 程式設計

一、從設計模式說起

近來寫 GridView 與 Gallery,處處都要用到 Adapter,於是乾脆專門查了一下。

Adapter 是 Java 裡常見的設計模式,目的是讓兩個原本不相干的類別能協同運作。打個比方:水管 A 口徑 25mm,水管 B 口徑 40mm,要把它們接在一起,就需要一段一頭 25mm、一頭 40mm 的轉接頭。Adapter 扮演的正是這個角色。

二、Android 中的 Adapter

在 Android 裡,Adapter 是 View 與 Data 之間的橋樑:它一方面提供對資料的存取,另一方面負責為每一筆資料產生對應的視圖。三者關係可以概括為:資料交給 Adapter,Adapter 生成子視圖,容器負責排列顯示。

Adapter 家族成員眾多,其中 BaseAdapter 因為最靈活而最常使用;SimpleCursorAdapter 也相當常見,它能直接綁定 Cursor 來顯示資料。

三、四個關鍵方法

無論繼承哪一種 Adapter,以下四個方法幾乎都要重載:

// 資料共有幾項
int getCount();

// 回傳指定位置的資料項
Object getItem(int position);

// 回傳指定位置資料項的 ID
long getItemId(int position);

// 為每一筆資料產生對應的視圖
View getView(int position, View convertView, ViewGroup parent);

有朋友翻過原始碼後發現,getItem() 與 getItemId() 對 Android 本身其實沒有實際作用,純粹是為了呼叫端方便;我曾嘗試只重載這兩個方法來設定初始 position,結果完全沒有效果——真正決定顯示內容的是 getView()。

四、SimpleCursorAdapter 的簡單範例

擴展 BaseAdapter 的自訂寫法在 ListView、GridView、Gallery 相關文章中已有說明,這裡示範如何用 SimpleCursorAdapter 讀取聯絡人:

listView = new ListView(this);

// 查詢系統的聯絡人資料表
Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
startManagingCursor(cursor);

ListAdapter listAdapter = new SimpleCursorAdapter(
        this,                                          // 上下文
        android.R.layout.simple_expandable_list_item_1, // 項目版面
        cursor,                                        // 資料源
        new String[] { People.NAME },                  // 對應的資料欄位
        new int[] { android.R.id.text1 });             // 要顯示到哪個控制項

listView.setAdapter(listAdapter);
setContentView(listView);

五個參數的順序值得記住:上下文、版面資源、Cursor、資料欄位陣列、控制項 id 陣列——後兩者一一對應,位置不能錯位。

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