Android中listview只能将item逐行显示,不能实现树形效果,ExpandableListView是对listView的扩充,可以显示 类似QQ列表的效果,ExpandableListView只支持二级列表。ExpandableListView的使用与ListView类似。下面是我写的小例子
首先继承BaseExpandableListAdapter
public class MyAdapter extends BaseExpandableListAdapter {
private List<List<Map<String,String>>> group;
Context context;
public MyAdapter(List<List<Map<String,String>>> data,Context context){
this.group=data;
this.context=context;
}
//返回组的数量
@Override
public int getGroupCount() {
return group.size();
}
//返回组内的children数量
@Override
public int getChildrenCount(int groupPosition) {
return group.get(groupPosition).size();
}
@Override
public Object getGroup(int groupPosition) {
return group.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return group.get(groupPosition).get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
//对一级目录进行填充
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView==null){
convertView=LayoutInflater.from(context).inflate(R.layout.group_view,null);
viewHolder=new ViewHolder();
viewHolder.imageView=(ImageView)convertView.findViewById(R.id.g_image);
viewHolder.textView=(TextView)convertView.findViewById(R.id.g_text);
convertView.setTag(viewHolder);
}
else{
viewHolder=(ViewHolder)convertView.getTag();
}
viewHolder.imageView.setImageResource(R.mipmap.ic_launcher);
viewHolder.textView.setText("group");
return convertView;
}
//填充子目录
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView==null){
convertView=LayoutInflater.from(context).inflate(R.layout.group_view,null);
viewHolder=new ViewHolder();
viewHolder.imageView=(ImageView)convertView.findViewById(R.id.g_image);
viewHolder.textView=(TextView)convertView.findViewById(R.id.g_text);
convertView.setTag(viewHolder);
}
else{
viewHolder=(ViewHolder)convertView.getTag();
}
viewHolder.imageView.setImageResource(R.mipmap.ic_launcher);
viewHolder.textView.setText(group.get(groupPosition).get(childPosition).get("name"));
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
//ViewHolder保存每个item内的view
static class ViewHolder{
ImageView imageView;
TextView textView;
}
}
然后写两个布局文件,布局文件可参考ListView的写法。