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

Android ResourceCursorAdapter API 解析:以 XML 版面配置建立清單檢視

編輯:Android 開發實例

ResourceCursorAdapter 是 CursorAdapter 的抽象子類別,主要用途是根據指定的 XML 版面配置建立清單項目檢視。它讓開發者能以資源檔方式定義列表外觀,再把 Cursor 資料綁定到檢視中。

類別結構

ResourceCursorAdapter 繼承自 CursorAdapter,而 CursorAdapter 又屬於 BaseAdapter 體系。常見的直接子類別是 SimpleCursorAdapter。

建構子

ResourceCursorAdapter 常見建構方式如下:

ResourceCursorAdapter(Context context, int layout, Cursor c)

另一個版本可加入 autoRequery 參數:

ResourceCursorAdapter(Context context, int layout, Cursor c, boolean autoRequery)

參數意義:

  • context:應用程式上下文。
  • layout:列表項目使用的版面配置資源。
  • c:提供資料的 Cursor。
  • autoRequery:若為 true,資料變更時會重新查詢 Cursor。

主要方法

newView

newView(Context context, Cursor cursor, ViewGroup parent) 會依指定的 XML 版面配置建立新的檢視。cursor 已移動到正確位置,可直接讀取資料。

newDropDownView

newDropDownView(Context context, Cursor cursor, ViewGroup parent) 用於建立下拉式檢視,常見於 AutoCompleteTextView 等元件。

setDropDownViewResource

setDropDownViewResource(int dropDownLayout) 可設定下拉檢視的版面配置資源。

setViewResource

setViewResource(int layout) 可設定一般列表項目的版面配置資源。

使用情境

ResourceCursorAdapter 適合需要將資料庫查詢結果轉為清單的情境。若列表項目只是簡單文字,可使用 SimpleCursorAdapter;若需要更複雜的行為,例如快取檢視元件、自訂點擊效果、動態載入圖片,則可繼承 ResourceCursorAdapter 並覆寫 bindView()。

範例概念

常見流程如下:

  1. 查詢聯絡人或其他資料來源,取得 Cursor。
  2. 建立 ResourceCursorAdapter 子類別,指定版面配置。
  3. 在 newView() 中載入版面配置並快取子檢視。
  4. 在 bindView() 中將名稱、狀態、相片或聯絡資訊填入檢視。
  5. 透過 ListActivity 或 ListView 設定 Adapter。

效能建議

在 bindView() 中應避免昂貴操作。可將 findViewById 結果快取於 tag 或自訂 holder 物件中,並避免在每次綁定時重新建立大量物件。若資料量龐大,應搭配合理查詢、分頁或資料庫索引。

ResourceCursorAdapter 讓 Cursor 資料能與 XML 版面配置結合,是 Android 清單開發中非常實用的基礎類別。

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