一、创建手风琴
要创建手风琴,有两种方式。
1.在XML中申明
<ExpandableListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/expand"
></ExpandableListView>
2. 继承ExpandableListActivity
final String[] groups = { "家人", "朋友", "同事" };
final String[][] children = { { "老爸", "老妈", "姐姐", "老婆" },
{ "啊腾", "小永", "金文" }, { "陈老板", "书榕" } };
ExpandableListAdapter adapter = new ExpandableListAdapter() {
TextView getChildContent(){
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, 64);
TextView textView = new TextView(MainApp.this);
textView.setLayoutParams(lp);
// Center the text vertically
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
textView.setPadding(54, 0, 0, 0);//54表示textview本身与父对象的距离
textView.setTextSize(18);
return textView;
}
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
TextView view=getChildContent();
view.setText(getChild(groupPosition, childPosition).toString());
return view;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
//LinearLayout layout=new LinearLayout(MainApp.this);
/*设置按钮
* layout.setOrientation(0);
ImageView logo = new ImageView(ExpandableListViewTest.this);
logo.setImageResource(logos[groupPosition]);
layout.addView(logo);*/
TextView textview=getChildContent();
textview.setText(getGroup(groupPosition).toString());
//layout.addView(textview);
return textview;
}
@Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return children[groupPosition].length;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return children[groupPosition][childPosition];
}
@Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
@Override
public int getGroupCount() {
// TODO Auto-generated method stub
return groups.length;
}
@Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return groups[groupPosition];
}
其他重写的方法就略过了
expand = (ExpandableListView) findViewById(R.id.expand);
expand.setAdapter(adapter);
expand.setChildIndicator(getResources().getDrawable(R.drawable.home));
//设置图标
expand.setOnChildClickListener(new OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(MainApp.this, children[groupPosition][childPosition], 1).show();
return false;//isChildSelectable方法必须返回true
}
});
下载代码,点击这里