在上面幾次學習中,我們學習了如何在一個有限的螢幕上載入多頁的資訊,除此之外還可以通過隱藏-展開的方式,在螢幕有限的空間內包含更多的現象,,這就是ExpandableListView。
ExpandableListView,具有樹的結構:Groups和childrens。下面我們通過一個簡單的例子來學習,這個例子的資料不再採用String[],而是採用另一個常見的HashMap方式,順帶複習一下。
public class Chapter9Tutorial4 extends ExpandableListActivity{
private static final String NAME="NAME";
//這是HashMap的Key名稱
private static final String IS_EVEN = "IS_EVEN";
//這是HashMap的Key名稱
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//步驟1:設定ExpandableListActivity的Group和Chlid的資料
//在這個例子中,Group的儲存格式為HashMap<String,String>所以其格式為List<儲存格式
//Child中最基礎的item格式也為HashMap<String,String>,因此每一個Group中包含的child的格式為List<基礎儲存格式>,而所有的Group又是List,因此所有的child的格式為List<每個Group的child格式>,即List<List<基礎儲存格式>>
List<Map<String ,String>> groupData = new ArrayList<Map<String,String>>();
List<List<Map<String ,String>>> childData = new ArrayList<List<Map<String ,String>>>();
for(int i = 0 ; i< 6 ; i++){
Map<String, String> curGroupMap = new HashMap<String, String>();
groupData.add(curGroupMap);
curGroupMap.put(NAME, "Group " +i);
curGroupMap.put(IS_EVEN, "Hello " + i);
List<Map<String,String>> children = new ArrayList<Map<String,String>>();
for(int j = 0; j < 3; j++){
Map<String ,String > curChildMap = new HashMap<String,String>();
children.add(curChildMap);
curChildMap.put(NAME, "Child " + j + " for group " + i);
curChildMap.put(IS_EVEN, "From Group " + i + " Hello my friend!");
}
childData.add(children);
}
//步驟2:設定ExpandableList的adapter,ExpandableListAdapter是個介面,對於Map方式可使用SimpleExpandableListAdapter
ExpandableListAdapter mAdapter = new SimpleExpandableListAdapter(
this,
groupData,
android.R.layout.simple_expandable_list_item_1,
new String[]{NAME,IS_EVEN},
new int[] {android.R.id.text1,android.R.id.text2},
childData,
android.R.layout.simple_expandable_list_item_2,
new String[]{NAME,IS_EVEN},
new int[] {android.R.id.text1,android.R.id.text2}
);
setListAdapter(mAdapter);
}
//步驟3:觸發處理,包括有:OnChildClickListener,OnGroupClickListener,OnGroupCollapseListener和OnGroupExpandListener。在這個例子中每個child的View的類型是TwoLineListItem
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Log.d("WEI","Click: [" + groupPosition + "," + childPosition + "] ");
return super.onChildClick(parent, v, groupPosition, childPosition, id);
}
}
相關連結:我的Andriod開發相關文章