1、初步认识
ExpandableView是ListView的一个子类,它在普通的ListView的基础上进行了拓展,可以把应用中的列表分成几个组,每组又包含多个列表项。
ExpandableView的使用场景:
适用于两层分组
2、简单使用
ExpandableListView的使用方式和ListView一致,也是使用Adapter进行数据的填充
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.tjstudy.expandablelistviewdemo.MainActivity">
<ExpandableListView
android:id="@+id/elv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:listSelector="#00000000"/>
</LinearLayout>
使用:
/**
* 设置ExpandableView适配器
*/
private void setELVData() {
elv.setAdapter(new BaseExpandableListAdapter() {
//设置总得分组
@Override
public int getGroupCount() {
return 3;
}
//设置每个分组有多少个小项
@Override
public int getChildrenCount(int groupPosition) {
return 2;
}
@Override
public Object getGroup(int groupPosition) {
return null;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return true;
}
//设置组的界面
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View view = View.inflate(MainActivity.this, R.layout.group_view, null);
return view;
}
//设置组里面的项的界面
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View view = View.inflate(MainActivity.this, R.layout.child_view, null);
return view;
}
//设置小项是否可以点击 一般设置都是可以点击
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
});
}
关键点:
getGroupView()设置组的view,getChildView()设置子项的view
效果:
注意观察效果图,发现ExpandableListView的分组是设置有默认图标的,
如果需要该图标可以直接组界面位置 ,使得控件默认的图标能够显示出来
如果你想要自己定义要使用哪张图片:
1)、将ExpandableView的默认图标设置为空–
elv.setGroupIndicator(null);//设置ExpandableListView默认的分组图片标识不显示
2)、设置自己想要的效果
在group_view里面添加ImageView来存放自己的标识,
在getGroupView里面对标识进行设置
ImageView ivGroupIcon = (ImageView) view.findViewById(R.id.iv_group_icon);
if (isExpanded) {
ivGroupIcon.setImageResource(R.mipmap.down_arrow);
} else {
ivGroupIcon.setImageResource(R.mipmap.right_arrow);
}
效果:
demo地址:
http://download.youkuaiyun.com/detail/u012391876/9607535