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

Android Adapter 入門:以 SimpleAdapter 輕鬆綁定清單資料

編輯:Android 開發實例

當你想自訂列表顯示時,Adapter 是不可或缺的好幫手,其中又以 SimpleAdapter 最為常用。它的建構子如下:

public SimpleAdapter (Context context, List<Map<String, ?>> data, int resource, String[] from, int[] to)

各參數的意義如下:

context:上下文,即 SimpleAdapter 關聯的視圖,一般就是目前的 Activity,可直接傳入 this。
data:泛型的 List,例如 ArrayList,內容多為 Map 或 HashMap。
resource:資源檔,一個 R.layout,也就是要顯示的版面配置。
from:一個陣列,對應 Map 中的鍵值。
to:對應 layout XML 中元件 id 所形成的 int 識別碼。

實作範例

在 ListActivity 中先定義一個 List 並塞入資料:

List<Map<String, String>> people= new ArrayList<Map<String, String>>();
Map m=new HashMap();
m.put("name","tom");
m.put("age","20");
people.add(m);
...
SimpleAdapter adapter = new SimpleAdapter(this, (List<Map<String, String>>) people, R.layout.main,
new String[] { "name","age" }, new int[] {R.id.name,R.id.age });
setListAdapter(adapter);

其中 R.id.name 與 R.id.age 是在 XML 版面配置中定義的兩個 TextView,分別用來顯示 name 與 age,而版面中還需包含一個 ListView(也可以在程式中動態建立)。

小提醒:在 ListActivity 中不需要呼叫 setContentView,系統會自動載入預設版面。

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