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

ListView 入門實作:用 SimpleAdapter 打造圖文列表

編輯:關於 Android 程式設計

ListView 是 Android 最歷史悠久的垂直列表元件。它本身只負責「怎麼排」,資料怎麼來、每一列長什麼樣,交給 Adapter 與資料集決定——這正是典型 MVC 的分工方式。

兩種建立方式

第一種直接在配置檔放 <ListView> 標籤,於 Activity 中 findViewById 取得;第二種讓 Activity 繼承 ListActivity,用 setListAdapter() 直接餵資料。新手建議先用第一種,控制力比較直觀。

幾個關鍵屬性

  • android:entries:直接指定一個字串陣列資源,Android 會自動幫你生出一份清單,最省事的寫法。
  • android:divider:設定列表項之間的分隔線,顏色或 Drawable 都可以。

配置檔

這裡刻意把 ListView 與用來呈現內容的 ImageView、TextView 並列在 LinearLayout 中,而不是把子檢視塞進 ListView 內部——原因後面會說明。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20sp" />
</LinearLayout>

Activity 端組裝資料

SimpleAdapter 的做法是把資料整理成一串 Map,再告訴它「哪個 key 對應哪個 View」。

ListView listView = (ListView) findViewById(R.id.list);

List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
for (int i = 0; i < names.length; i++) {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("name",  names[i]);
    map.put("image", images[i]);
    maps.add(map);
}

SimpleAdapter adapter = new SimpleAdapter(this, maps, R.layout.item,
        new String[] { "name", "image" },
        new int[] { R.id.textView, R.id.imageView });
listView.setAdapter(adapter);

五個建構參數的意思

  1. context:上下文環境。
  2. data:List<Map<String, ?>>,每個 Map 產生一列。
  3. resource:單一列的外觀配置檔 id。
  4. from:String 陣列,內容是 Map 的 key,用來取值。
  5. to:int 陣列,指定用哪些 View 來顯示上一步取出的值。

踩過的坑

一開始把 ImageView、TextView 直接寫在 ListView 標籤內部,執行時丟出:

java.lang.UnsupportedOperationException:
addView(View, LayoutParams) is not supported in AdapterView

原因在於 AdapterView 系列不允許 arbitrary 的子檢視寫在配置檔裡,它的內容必須由 Adapter 產生。正確觀念是:ListView 只留一個空殼,真正用來顯示單列內容的版面另外開一個配置檔,再交給 Adapter 指定。養成這個習慣,後面換成 BaseAdapter 自訂一列樣式時也會順很多。

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