Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android ListView 資料綁定:SimpleAdapter 與 SimpleCursorAdapter 實戰對比

要把資料庫裡的記錄一條條列出來,ListView 是最基本的工具。但 ListView 本身只負責排列,資料與畫面之間必須靠 Adapter 搭橋,而常見的搭橋方式有兩種。

兩種 Adapter 的選擇依據

  • SimpleAdapter:資料必須先整理成 List,且每個元素是 HashMap,適合資料來源為物件集合、需要加工後再顯示的情況。
  • SimpleCursorAdapter:資料必須是 Cursor,直接把查詢結果交給它,省去手動轉換,但有一個硬性要求——查詢結果必須包含名為 _id 的主鍵欄位。

版面:item.xml 與 main.xml

item.xml 是一列的外觀:一個水平的 LinearLayout,內含三個 TextView,id 分別為 name、phone、amount,寬度依序為 130dp、150dp 與 fill_parent。

main.xml 則是「標題列 + 清單」的結構:外層垂直 LinearLayout,第一個子元素是水平 LinearLayout,放三個文字分別為「姓名」、「電話」、「存款」的 TextView,寬度需與 item 對齊;第二個子元素才是 id 為 listView、寬高皆為 fill_parent 的 ListView。標題與資料欄位寬度一致,畫面才不會歪。

做法一:SimpleAdapter

先取得服務層的分頁資料,再把每個 Person 物件攤平成 HashMap,最後交給 SimpleAdapter 指定要對應的欄位與 view id:

List persons = service.getScrollData(0, 10);
List data = new ArrayList();
for (Object o : persons) {
    HashMap item = new HashMap();
    item.put("name", person.getName());
    item.put("phone", person.getPhone());
    item.put("amount", person.getAmount());
    data.add(item);
}

SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,
        new String[]{"name", "phone", "amount"},
        new int[]{R.id.name, R.id.phone, R.id.amount});
listView.setAdapter(adapter);

點擊時用 getItemAtPosition(position) 取回該列的 HashMap,就能取出 id 或其他欄位:

HashMap data = (HashMap) listView.getItemAtPosition(position);
String personid = data.get("id").toString();

做法二:SimpleCursorAdapter

游標版本省掉了整段轉換迴圈,程式碼短很多:

Cursor cursor = service.getCursorScrollData(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);

但點擊時取回的是 Cursor,必須自行以 getColumnIndex 定位欄位,而 _id 正是靠這個方式取出:

Cursor cursor = (Cursor) listView.getItemAtPosition(position);
String personid = String.valueOf(cursor.getInt(cursor.getColumnIndex("_id")));

該選哪一個

資料量小、需要顯示加工過的欄位(例如把存款加上千位分隔、換算幣別)時用 SimpleAdapter;資料直接來自 SQLite 查詢、欄位與畫面一一對應時用 SimpleCursorAdapter。若使用後者,別忘了在 SELECT 中明確帶入 _id,否則執行期才會發現點擊永遠取不到主鍵。清單很長時,兩者都建議搭配自訂 BaseAdapter 與 ViewHolder 做視圖重用,才能避免滾動卡頓。

Copyright © Linux教程網 All Rights Reserved