之前的博文《Android中使用ExpandableListView实现好友分组》我简单介绍了使用ExpandableListView实现简单的好友分组功能,今天我们针对之前的所做的仿微信APP来对ExpandableListView做一个扩展介绍,实现效果如下(通讯里使用ExpandableListView实现):
相关知识点博文链接:
Android中使用ExpandableListView实现好友分组
Android中Fragment和ViewPager那点事儿
Android中ListView实现图文并列并且自定义分割线(完善仿微信APP)
正常使用ExpandableListView的思路如下:
(1)要给ExpandableListView 设置适配器,那么必须先设置数据源。
(2)数据源,就是此处的适配器类ExpandableAdapter,此方法继承了BaseExpandableListAdapter ,它是ExpandableListView的一个子类。需要重写里面的多个方法。方法的意思,代码中都有详细的注释。数据源中,用到了自定义的View布局,此时根据自己的需求,来设置组和子项的布局样式。getChildView()和getGroupView()方法设置自定义布局。
(3)数据源设置好,直接给 ExpandableListView.setAdapter()即可实现此收缩功能。
但本次实现除以上实现步骤之外,还需要注意的有以下几点:
在给ExpandableListView 设置适配器后,添加以下代码:
//Group.size()为组名个数,如果为数组存储则为group、length
for (int i = 0; i < Group.size(); i++) {
expandableListView.expandGroup(i);
}
expandableListView.setOnGroupClickListener(new OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
return true;//返回true则表示无法收缩
}
});
(3)取消通讯录上方的groupName空间
第一步:layout中通讯录整体布局contactfragment.xml:
其实就是一个ExpandableListView,添加android:divider ="#FFFFFF"取消自带分割线
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/fragmentback">
<ExpandableListView
android:id="@+id/contact_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:divider ="#FFFFFF"/>
</LinearLayout>
第二步:layout中组名(groupName)的布局文件contact_list_group_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width=&