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

Android ListView 資料綁定的三種方法詳解

編輯:關於 Android 程式設計

ListView 是 Android 中最常用的列表元件之一,而如何把資料「綁定」到列表上,則是每個開發者的必修課。本文將介紹三種由簡到繁的綁定方式,並示範如何回應列表項的點擊事件。

第一步:準備列表項佈局

先建立一個描述單一列表項外觀的佈局檔 item.xml,橫向排列三個 TextView:

<?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="horizontal" >
    <TextView
        android:id="@+id/name"
        android:layout_width="120dp"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/phone"
        android:layout_width="150dp"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/amount"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

接著在 main.xml 中加入一個 id 為 listview 的 ListView 控制項即可。

方法一:SimpleAdapter(Map 資料)

把資料整理成 List<HashMap>,再交給 SimpleAdapter 對應到 item 中的各個控制項:

private void show1() {
    List persons = ps.getScollData(0, 10);
    List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
    for (Person person : persons) {
        HashMap<String, Object> item = new HashMap<String, Object>();
        item.put("amount", person.getAmount());
        item.put("id", person.getId());
        item.put("name", person.getName());
        item.put("phone", person.getPhone());
        data.add(item);
    }
    SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(),
            data, R.layout.item,
            new String[]{ "name", "phone", "amount" },
            new int[]{ R.id.name, R.id.phone, R.id.amount });
    // 後兩個參數表示把資料中哪些 key 對應到哪些控制項
    listview.setAdapter(adapter);
}

方法二:SimpleCursorAdapter(Cursor 資料)

這種方式要求結果集的 Cursor 中必須有一個名為 _id 的欄位,因此在 SQL 查詢時需將主鍵別名為 _id:

private void show2() {
    Cursor cursor = ps.getCursorScollData(0, 10);
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor,
            new String[]{ "name", "phone", "amount" },
            new int[]{ R.id.name, R.id.phone, R.id.amount });
    listview.setAdapter(adapter);
}
public Cursor getCursorScollData(int offest, int maxResult) {
    SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(
        "select personid as _id,name,phone,amount from person order by personid asc limit ?,?",
        new String[]{ String.valueOf(offest), String.valueOf(maxResult) });
    return cursor;
}

方法三:自訂 BaseAdapter

最靈活的方式是自行定義 Adapter(詳見 BaseAdapter 章節),適合需要高度客製化列表項的場景:

private void show3() {
    List persons = ps.getScollData(0, 10);
    PersonAdapter adapter = new PersonAdapter(getApplicationContext(), persons, R.layout.item);
    listview.setAdapter(adapter);
}

回應列表項點擊

當使用者點擊某一項時,我們可以透過 setOnItemClickListener 取得該項的資料。三種綁定方式取回的物件型別各異,需分別處理:

listview.setOnItemClickListener(new ItemClickListener());

private final class ItemClickListener implements OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
        ListView lview = (ListView) parent;
        // show1 對應:adapter 回傳的是 Map
        HashMap<String, Object> item = (HashMap<String, Object>) lview.getItemAtPosition(position);
        int personid = (Integer) item.get("id");
        Toast.makeText(getApplicationContext(), personid + "", 1).show();
        // show2 對應:adapter 回傳的是 Cursor
        // Cursor cursor = (Cursor) lview.getItemAtPosition(position);
        // show3 對應:adapter 回傳的是 Person 物件
        // Person person = (Person) lview.getItemAtPosition(position);
    }
}

三種方法各有適用情境:SimpleAdapter 上手最快、SimpleCursorAdapter 適合直接吃資料庫游標、自訂 Adapter 則擁有最強的客製能力。理解它們的取用差異,就能依需求做出最佳選擇。

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