上類使用自訂的ExpandableListAdapter使用數組來定義Expandable list 的group 和 childern. 為ExpandableListAdapter之間的繼承關係
CursorTreeAdapter 支援使用一系列的Cursors 作為ExpandableListView 的資料來源,最上層的一個Cursor定義為Expandable的group ,其它的Cursor可以通過getChildernCursor為特定的Group定義其子Item。 所有的Cursor對象必須含有一個列名為”_id”的列,否則本類無法工作。
Cursor的用法可以參見Android ApiDemos樣本解析(10):App->Activity->QuickContactsDemo。
CursorTreeAdapter類名中帶有“Tree”,和其它平台中的TreeView不同,Expandable List只支援兩層。
ResourceCursorTreeAdapter 為CursorTreeAdapter 添加了兩個方法 newChildView和newGroupView 其建構函式允許為ExpandableListView 的group 和child 指定XML layout資源。
SimpleCursorTreeAdapter 提供了從表的列映射到TextView 或ImageView (在XML資源中定義)的簡便方法。你可以指定需要哪些列,每個列使用哪種View來顯示。
本例定義了SimpleCursorTreeAdapter 的子類MyExpandableListAdapter 使用Contact 通訊錄作為資料來源。
使用通訊錄中連絡人人名作為Group,而每個連絡人對應的所有電話號碼作為該group 的childeren.
[java]
Cursor groupCursor = managedQuery(People.CONTENT_URI,
new String[] {People._ID, People.NAME}, null, null, null);
// Cache the ID column index
mGroupIdColumnIndex = groupCursor.getColumnIndexOrThrow(People._ID);
// Set up our adapter
mAdapter = new MyExpandableListAdapter(groupCursor,
this,
android.R.layout.simple_expandable_list_item_1,
android.R.layout.simple_expandable_list_item_1,
new String[] {People.NAME}, // Name for group layouts
new int[] {android.R.id.text1},
new String[] {People.NUMBER}, // Number for child layouts
new int[] {android.R.id.text1});
Cursor groupCursor = managedQuery(People.CONTENT_URI,
new String[] {People._ID, People.NAME}, null, null, null);
// Cache the ID column index
mGroupIdColumnIndex = groupCursor.getColumnIndexOrThrow(People._ID);
// Set up our adapter
mAdapter = new MyExpandableListAdapter(groupCursor,
this,
android.R.layout.simple_expandable_list_item_1,
android.R.layout.simple_expandable_list_item_1,
new String[] {People.NAME}, // Name for group layouts
new int[] {android.R.id.text1},
new String[] {People.NUMBER}, // Number for child layouts
new int[] {android.R.id.text1});
其建構函式定義如下:
MyExpandableListAdapter(Cursor cursor, Context context, int groupLayout,
int childLayout, String[] groupFrom, int[] groupTo, String[] childrenFrom,
int[] childrenTo) {
cursor : group Cursor ,本例為連絡人名,可以看到此Cursor的列必須有一列為_ID.
context: context對象,可以使用activity。
groupLayout: Group Layout資源ID,本例使用系統資源simple_expandable_list_item_1.
childLayout: child Layout資源ID,本例使用系統資源simple_expandable_list_item_1。
groupFrom: 需要顯示的組列名數組,本例為Name
groupTo: 對應每個組的列對應的View 的id, 本例為一文本。
childrenFrom: 需要顯示的群組成員列名,本例為Number。
childrenTo:對應每個群組成員的列對應的View 的id, 本例為一文本。
作者:mapdigit