要把資料庫裡的記錄一條條列出來,ListView 是最基本的工具。但 ListView 本身只負責排列,資料與畫面之間必須靠 Adapter 搭橋,而常見的搭橋方式有兩種。
item.xml 是一列的外觀:一個水平的 LinearLayout,內含三個 TextView,id 分別為 name、phone、amount,寬度依序為 130dp、150dp 與 fill_parent。
main.xml 則是「標題列 + 清單」的結構:外層垂直 LinearLayout,第一個子元素是水平 LinearLayout,放三個文字分別為「姓名」、「電話」、「存款」的 TextView,寬度需與 item 對齊;第二個子元素才是 id 為 listView、寬高皆為 fill_parent 的 ListView。標題與資料欄位寬度一致,畫面才不會歪。
先取得服務層的分頁資料,再把每個 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();
游標版本省掉了整段轉換迴圈,程式碼短很多:
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 做視圖重用,才能避免滾動卡頓。