ExpandableListView是一种可折叠的列表视图,可以用来显示一组可以展开和折叠的分组列表。它可以用来展示一个多级列表,每个分组都可以展开和折叠。
使用步骤
- 1、创建一个ExpandableListView,并设置它的属性,如布局参数,背景等。
- 2、为ExpandableListView创建一个BaseExpandableListAdapter,实现它的getGroupView,getChildView,getGroupCount,getChildrenCount,getGroup,getChild等方法。
- 3、调用ExpandableListView的setAdapter方法,将BaseExpandableListAdapter设置给ExpandableListView。
- 4、调用ExpandableListView的setOnGroupClickListener方法,为ExpandableListView设置组点击事件,即当组被点击时,可以展开或折叠子列表。
- 5、调用ExpandableListView的setOnChildClickListener方法,为ExpandableListView设置子列表点击事件,即当子列表被点击时,可以做一些相应的操作。
示例代码
// 创建ExpandableListView ExpandableListView expandableListView = new ExpandableListView(this); // 设置布局参数 expandableListView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); // 为ExpandableListView设置适配器 expandableListView.setAdapter(adapter); // 为ExpandableListView设置组点击事件 expandableListView.setOnGroupClickListener(new OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { // TODO Auto-generated method stub return false; } }); // 为ExpandableListView设置子列表点击事件 expandableListView.setOnChildClickListener(new OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { // TODO Auto-generated method stub return false; } });
通过上述步骤,我们就可以使用ExpandableListView来显示一组可以展开和折叠的分组列表了。