ExpandableListView使用示例:
首先是布局文件:
<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" >
<ExpandableListView
android:id="@+id/expandableListView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ExpandableListView>
</LinearLayout>
下面是主函数:
public class MainActivity extends Activity {
public List<String> groups; //组列表
public List<List<String>> child; //子列表
ExpandableListView expandableListView;
mExpandableListAdapter adapter; //数据适配器
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
expandableListView = (ExpandableListView) findViewById(R.id.expandableListView1);
groups = new ArrayList<String>();
child = new ArrayList<List<String>>();
addInfo("张胜男", new String[]{"女","漂亮"}); //添加数据
addInfo("李子豪", new String[]{"男","帅气"});
addInfo("万古琴", new String[]{"女","温婉"});
addInfo("佘诗曼", new String[]{"女","好人"});
expandableListView.setAdapter(new mExpandableListAdapter());
}
private void addInfo(String g, String[] c){
groups.add(g);
List<String> childItem = new ArrayList<String>();
for(int i = 0; i < c.length; i++)
{
childItem.add(c[i]);
}
child.add(childItem);
}
class mExpandableListAdapter extends BaseExpandableListAdapter{
@Override
public Object getChild(int groupPosition, int childPosition) {
return child.get(groupPosition).get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(int arg0, int arg1, boolean arg2, View arg3,
ViewGroup arg4) {
String s = child.get(arg0).get(arg1);
return getGenericView(s);
}
@Override
public int getChildrenCount(int groupPosition) {
return child.get(groupPosition).size();
}
@Override
public Object getGroup(int arg0) {
return groups.get(arg0);
}
@Override
public int getGroupCount() {
return groups.size();
}
@Override
public long getGroupId(int arg0) {
return arg0;
}
@Override
public View getGroupView(int groupPosition, boolean arg1, View convertView, ViewGroup arg3) {
String s = groups.get(groupPosition);
return getGenericView(s);
}
//创建组/子视图
public TextView getGenericView(String s) {
// Layout parameters for the ExpandableListView
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 64);
TextView text = new TextView(MainActivity.this);
text.setLayoutParams(lp);
// Center the text vertically
text.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
text.setPadding(36, 0, 0, 0);
text.setText(s);
return text;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int arg0, int arg1) {
return true;
}
}
}
运行结果如下图: