1.在布局文件中创建ExpandableListView组件。
Activity中 获取ExpandableListView。
2.创建ExpandableListView的适配器ExpandableListAdapter,源码如下:
ExpandableListAdapter adapter = new BaseExpandableListAdapter() {
int[] logos = {R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher} ;
private String[] armtype = new String[]{"j1","j2","j3"} ;
private String[][] arms = new String[][]
{
{"jjj1","jj2","jj3"},
{"f2","f2","f3"},
{"w1","w2","w3"}
} ;
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true ;
}
@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true ;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LinearLayout ll = new LinearLayout(getApplicationContext()) ;
ll.setOrientation(0) ;
ImageView logo = new ImageView(getApplicationContext()) ;
logo.setImageResource(logos[groupPosition]) ;
ll.addView(logo) ;
TextView textview = getTextView() ;
textview.setText(getGroup(groupPosition).toString()) ;
ll.addView(textview) ;
return ll;
}
@Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition ;
}
@Override
public int getGroupCount() {
// TODO Auto-generated method stub
return armtype.length;
}
@Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return armtype[groupPosition];
}
@Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return arms[groupPosition].length;
}
private TextView getTextView(){
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,64) ;
TextView textView = new TextView(MainActivity.this) ;
textView.setLayoutParams(lp) ;
textView.setGravity(Gravity.CENTER_VERTICAL|Gravity.LEFT) ;
textView.setPadding(36, 0, 0, 0) ;
textView.setTextSize(20) ;
return textView ;
}
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TextView text = getTextView() ;
text.setText(getChild(groupPosition, childPosition).toString()) ;
return text ;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(), childPosition+"", 3000).show() ;
return childPosition;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return arms[groupPosition][childPosition];
}
}
3.添加适配器
ExpandableListView expand = (ExpandableListView)findViewById(R.id.expand) ;
expand.setAdapter(adapter) ;
效果如下: