当前位置:操作系统 > 安卓/Android >>

Android ApiDemos示例解析(113):Views->Expandable Lists->2. Cursor(People)

上类使用自定义的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

补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,