ListView -- MarsChen Android 開發教程學習筆記


ListView 的基本使用
1、創建Activity 繼承自ListActivity,兩個佈局文件。
一個是常用的main.xml ,線性佈局,嵌入listView ,用Android 內置ID:“android:list”,並且包含兩個命令行。
另一個是控制list 的佈局文件user.xml,在一個線性佈局文件中嵌套兩個textView 。線性佈局是橫向排列,兩個textView  代表每一欄中橫向排列兩個字符。
2、Activity 文件中創建HashMap 對象,代表每欄中的數據,每個HashMap 內放兩個鍵值對。調用put 方法放置兩個鍵值對。
HashMap<String, String> map1 = new HashMap<String, String>();
HashMap<String, String> map2 = new HashMap<String, String>();
HashMap<String, String> map3 = new HashMap<String, String>();
map1.put("鍵" , "值");
map1.put("鍵" , "值");
map2.put("鍵" , "值");
map2.put("鍵" , "值");
map3.put("鍵" , "值");
map3.put("鍵" , "值");

3、Activity 文件中創建ArrayList<HashMap<String, String>> 的list 對象,調用add 方法將HashMap 對象加入列表形成完整的ListView 形態。
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>
list.add(map1);
list.add(map2);
list.add(map3);


4、還要創建一個SimpleAdapter 對象listAdapter ,第一個參數代表Activity ,第二個即使ArrayList 對象,第三個參數代表放置表格內容的XML 文件,即上文中的user.xml ,第四個參數是字符數組,列表有幾列數組就有幾個參數數組中的參數放置的是鍵值對中的鍵,第五個參數是一個int 數組,放置兩個R.id,對應user.xml 文件中的兩個textView 。

SimpleAdapter listAdapter = new SimpleAdapter(this ,list ,R.layout.user ,new String[]{"user_name","user_ip"} ,new int[]{R.id.user_name,R.id.user_ip} );


5、最後要設置適配器

setListAdapter(listAdapter);



ExpandableListActivity 和SimpleExpandableListAdapter 的基本使用
ExpandableListeActivity 是列表組。

1、創建一個Activity 繼承ExpandableListActivity 。
分別創建兩種Map和List 成對的對象,一種是一級條目的,一種是二級條目的。創建和使用方法與listView 相同,當然還要用put 和 add 方法。
List<Map<String, String>> groups = new ArrayList<Map<String, Stirng>>();
Map<String, String> group = new HashMap<String,String>>();
List<Map<String, String>> child1 = new ArrayList<Map<String, Stirng>>();
Map<String, String> child1data1= new HashMap<String,String>>();


定義一個list 對象,存放所有二級條目。
List<List<Map<String, String>>> childs = new ArrayList<List<Map<String, String>>>();
childs.add(child1);
childs.add(child2);


2、除了原先的默認XML 文件之外還要創建兩個佈局文件,分別代表組和組值。
默認XML 文件中添加ExpandableListView 的標籤,ID直接引用Android 設定好的“android:list”,並在標籤內添加android:drawSelectorOnTop="false",代表被選擇的時候顏色是否覆蓋所選列表。
第一個和第二個XML文件仍和listView 一樣放置TextView ,兩者區別不過是字體大小不同。

3、生成SimpleExpandableListAadapter 對象,第一個參數是Activity,第二個參數是一級條目的數據,第三個參數用來設置一級條目樣式的佈局文件,第四個參數指定一級條目

數據的鍵,第五個參數指定一級條目的id,第六個參數指定二級條目樣式的佈局文件,第七個參數指定二級條目的鍵,第八個指定二級條目的id 。

SimpleExpandableListAdapter sela = new SimpleExpandableListAdapter(this, groups, R.layout.group, new String[]{"group"}, new int[] {R.id.group}, childs , R.layout.child , new String[]{"child"},new int[]{R.id,child});

4、

setListAdapter(sela);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章