Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android ListActivity 綁定資料庫資料

編輯:Android 開發實例

ListActivity 簡介

ListActivity 是專門用來顯示列表的 Activity,可透過 setListAdapter 綁定資料來源。若資料來自 SQLite,常會搭配 Cursor 與 SimpleCursorAdapter。

查詢資料庫

Cursor cursor = db.query(
    TABLE_NAME,
    new String[]{TABLE_ID, TABLE_TITLE, TABLE_URL},
    null, null, null, null, null
);

使用 SimpleCursorAdapter

SimpleCursorAdapter adapter = new SimpleCursorAdapter(
    this,
    android.R.layout.simple_expandable_list_item_1,
    cursor,
    new String[]{TABLE_TITLE},
    new int[]{android.R.id.text1}
);

setListAdapter(adapter);

這樣 ListView 就會顯示 cursor 中的 title 欄位。若要顯示更多欄位,可改用自訂 layout 與自訂 Adapter。

使用 SimpleAdapter 綁定靜態資料

若資料不是來自資料庫,也可使用 List 與 Map:

ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", "chenxi");
map.put("ip", "192.168.1.0");
list.add(map);

SimpleAdapter adapter = new SimpleAdapter(
    this,
    list,
    R.layout.a3,
    new String[]{"name", "ip"},
    new int[]{R.id.name, R.id.ip}
);

setListAdapter(adapter);

注意事項

使用 Cursor 時,若 Activity 生命週期結束,建議妥善關閉或交由系統管理,避免游標洩漏。若列表項目點擊後要傳值到其他 Activity,可透過 position 取得對應資料,再放入 Intent。

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