首先我們先看一下簡單的ArrayAdapter:ListActivity不同於普通Activity的地方是該Activity裏邊有一個ListView,該ListView綁定了Adapter中的數據。在這個示例中,該ListView綁定了包含三個元素的ArrayList,這三個元素分別是”1, 2, 3”。
主要代碼:
首先我們需要讓我們的類繼承於ListActivity
1: pubic class ListActivityTest extends ListActivity
2: {
3: …..
4: }
讓我們直接看代碼吧:
1: public class ListActivityTest extends ListActivity
2: {
3: /** Called when the activity is first created. */
4: @Override
5: public void onCreate(Bundle savedInstanceState)
6: {
7: super.onCreate(savedInstanceState);
8: this.setTheme(android.R.style.Theme_Black);
9: // setContentView(R.layout.main);
10:
11: List items = fillArray();
12:
13: ArrayAdapter adapter = new ArrayAdapter(
14: this, android.R.layout.simple_expandable_list_item_1, items);
15: this.setListAdapter(adapter);
16: }
17:
18: private List fillArray()
19: {
20: List items = new ArrayList();
21: items.add("1");
22: items.add("2");
23: items.add("3");
24: return items;
25: }
26: }
fillArray()返回了一個有三個String對象的List集合,我們在後邊用來綁定ListView顯示的內容。
然後我們需要在類中的onCreate()函數裏邊添加如下內容:
List items = this.getData(); // 獲得待綁定的集合
ArrayAdapter adapter = new ArrayAdapter(
this, android.R.layout.simple_expandable_list_item_1,
items);
this.setListAdapter(adapter);
其中:this代表當前的Context;android.R.layout.simple_expandable_list_item_1代表一個包含ListView的layout的ID,系統自帶了幾種,我們在這裏選擇的是系統自帶的;items表示被綁定的數據源。
OK,簡單的看完我們就可以看複雜一點的SimpleAdapter:
我們還是先來看一下效果:
先上代碼:
1: public class ListActivityTest extends ListActivity
2: {
3: /** Called when the activity is first created. */
4: @Override
5: public void onCreate(Bundle savedInstanceState)
6: {
7: super.onCreate(savedInstanceState);
8:
9: List> listContent = this.getData();
10:
11: SimpleAdapter adapter = new SimpleAdapter(this,
12: listContent,
13: android.R.layout.simple_list_item_2,
14: new String[] {"Name", "Address"},
15: new int[] {android.R.id.text1, android.R.id.text2});
16:
17: setListAdapter(adapter);
18: }
19:
20: private List> getData()
21: {
22: List> listContent = new ArrayList>();
23:
24: Hashtable table1 = new Hashtable();
25: table1.put("Name", "LiLi");
26: table1.put("Address", "China");
27: listContent.add(table1);
28:
29: Hashtable table2 = new Hashtable();
30: table2.put("Name", "NiuNiu");
31: table2.put("Address", "ChinaHeibei");
32: listContent.add(table2);
33:
34: return listContent;
35: }
36: }
講解:
SimpleAdapter可以實現比ArrayAdapter更加複雜的ListView界面,我們這個程序實現的是一項中有兩行文字的ListView。
其中的getData()函數返回的是一個List,這個不懂的朋友請查閱相關的Java基礎資料。在onCreate()函數中構造了一個SimpleAdapter(),我們看一下SimpleAdapter()的構造函數:
SimpleAdapter(Context context, List> data, int resource, String[] from, int[] to)
其中:
context : 當前的環境上下文,一般直接傳遞this就OK
Data:數據源,我們之前構造的listContent就是該ListView的數據源
resource:layout模板資源,我們可以傳遞Android自帶的,當然也可以自定義,我們在這裏爲了簡單傳遞的是Android自帶的
from和to:這個我們需要聯合起來看,這兩個是平行數組,也就是數組的大小相同,根據我們的例子,我們需要在android.R.id.text1中顯示數據源中索引爲”name”的項,在android.R.id.text2種顯示索引爲”address”的項。