注意点:1)适配器BaseExpandableListAdapter
2)数据源(数组、集合都行)(重点)
/**
* Created by mb on 2014/11/18.
* 二级菜单适配器
*/
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
List<String> groups;//String [] groups = {};
List<List<MB>> childs; //String [] [] childs = {{},{},};
ViewHolder holder;
public MyExpandableListAdapter(Context context, List<String> groups, List<List<MB>> childs) {
this.context = context;
this.groups = groups;
this.childs = childs;
}
@Override
public int getGroupCount() {
return groups.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return childs.get(groupPosition).size();
}
@Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return childs.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 true;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView1, ViewGroup parent) {
//自定义组视图
return convertView1;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
//自定义孩子视图
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public static class ViewHolder {
//控件
}
}
事件监听:
myExpandableListAdapter = new MyExpandableListAdapter(context, groups, childs);
expandableListView.setAdapter(myExpandableListAdapter);
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
int count = myExpandableListAdapter.getChildrenCount(groupPosition);
if (count <= 0) {
activity.showCustomToast("...");
}
return false; // ---此处返回true 点击后不能展开组 具体原因知道的留言
}
});
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
return false;
}
});
默认展开所有菜单:
for (int i = 0; i < myExpandableListAdapter.getGroupCount(); i++) {
expandableListView.expandGroup(i);
}