上一期学习了AutoCompleteTextView和MultiAutoCompleteTextView,你已经掌握了吗?本期开始学习ExpandableListView的使用。
一、认识ExpandableListView
ExpandableListView 是 ListView 的子类,它在普通ListView的基础上进行了扩展,它把应用中的列表项分为几组,每组里又可包含多个列表项。
ExpandableListView的用法与普通 ListView的用法非常相似,只是 ExpandableListView所显示的列表项应 该由 ExpandableListAdapter 提供。ExpandableListAdapter 也是一个接口,该接口下提供的类继承关系图如下图所示。
与Adapter类似的是,实现 ExpandableListAdapter也有如下三种常用方式。
-
扩展 BaseExpandableListAdapter 实现 ExpandableListAdapter。
-
使用 SimpleExpandableListAdapter 将两个 List 集合包装成 ExpandableListAdapter。
-
使用 SimpleCursorTreeAdapter 将 Cursor 中的数据包装成 SimpleCursorTreeAdapter。
ExpandableListView支持的常用XML属性如下:
-
android:childDivider:指定各组内子类表项之间的分隔条,图片不会完全显示, 分离子列表项的是一条直线。
-
android:childIndicator:显示在子列表旁边的Drawable对象,可以是一个图像。
-
android:childIndicatorEnd:子列表项指示符的结束约束位置。
-
android:childIndicatorLeft:子列表项指示符的左边约束位置。
-
android:childIndicatorRight:子列表项指示符的右边约束位置。
-
android:childIndicatorStart:子列表项指示符的开始约束位置。
-
android:groupIndicator:显示在组列表旁边的Drawable对象,可以是一个图像。
-
android:indicatorEnd:组列表项指示器的结束约束位置。
-
android:indicatorLeft:组列表项指示器的左边约束位置。
-
android:indicatorRight:组列表项指示器的右边约束位置。
-
android:indicatorStart:组列表项指示器的开始约束位置。
二、ExpandableListView 示例
接下来通过一个简单的示例程序来学习ExpandableListView的使用方法。
继续使用WidgetSample工程的listviewsample模块,在app/main/res/layout/目录下创建expandlist_layout.xml文件,在其中填充如下代码片段:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ExpandableListView
android:id="@+id/expendlist"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
在res/layout/目录创建expendlist_group.xml文件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="70dp"
android:gravity="center_vertical"
android:padding="10dp">
<ImageView
android:id="@+id/group_img"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:src="@drawable/group_close" />
<TextView
android:id="@+id/groupname_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/group_img"
android:layout_marginLeft="10dp"
android:text="张三"
android:textSize="18sp" />
</RelativeLayout>
在res/layout/目录创建expendlist_item.xml文件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="horizontal"
android:gravity="center_vertical"
android:padding="10dp" >
<ImageView
android:id="@+id/icon_img"
andr