Android入门之ExpandableListView控件的使用

2014-11-24 11:17:53 · 作者: · 浏览: 2

本文通过学习ExpandableListView控件的使用,同时学习ExpandableListActivity类和SimpleExpandableListAdapter适配器的使用。


通过例子讲解,代码中有详细的注释:


首先layout中有3个布局文件:


main.xml


---------------------------------------------------------------------------


group.xml


< xml version="1.0" encoding="utf-8" >
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="no data"
android:id="@+id/tvgroup"
android:paddingBottom="10px"
android:paddingLeft="50px"

/>


--------------------------------------------------


child.xml


< xml version="1.0" encoding="utf-8" >
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="no data"
android:id="@+id/tvchild"
android:paddingLeft="50px"
/>


---------------------------------------------------------------------


java代码:


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import android.app.ExpandableListActivity;
import android.os.Bundle;
import android.widget.SimpleExpandableListAdapter;


public class ExpandableListActivityTest extends ExpandableListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);


List> groups = new ArrayList>();
Map group1 = new HashMap();
group1.put("group", "huangweiyong");


Map group2 = new HashMap();
group2.put("group", "xiaoqi");


Map group3 = new HashMap();
group3.put("group", "hahaha");

groups.add(group1);
groups.add(group2);
groups.add(group3);


List> child1 = new ArrayList>();
Map child1Data1 = new HashMap();
child1Data1.put("child", "child1Data1");
Map child1Data2 = new HashMap();
child1Data2.put("child", "child1Data2");
child1.add(child1Data1);
child1.add(child1Data2);


List> child2 = new ArrayList>();
Map child2Data1 = new HashMap();
child2Data1.put("child", "child1Data1");
child2.add(child2Data1);

List> child3 = new ArrayList>();
Map child3Data1 = new HashMap();
child3Data1.put("child", "child1Data1");
child3.add(child3Data1);


List>> childs = new ArrayList>>();
childs.add(child1);
childs.add(child2);
childs.add(child3);

/**
* 生成一个SimpleExpandableListAdapter对象
* 1、context
* 2、一级条目的数据
* 3、用来设置一级条目样式的布局文件
* 4、指定一级条目数据的key
* 5、指定一级条目数据显示的控件id
* 6、指定二级条目的数据
* 7、用来设置二级条目样式的布局文件
* 8、指定二级条目数据的key
* 9、指定二级条目数据显示的控件id
*/
SimpleExpandableListAdapter sela = new SimpleExpandableListAdapter(
this, groups, R.layout.group, new String[] { "group" },
new int[] { R.id.tvgroup }, childs, R.layout.child,
new String[] { "child" }, new int[] { R.id.tvchild });
//将适配器对象设置给ExpandableListActivity
setListAdapter(sela);
}
}