(转)ExpandableList的用法

在Android的app包中,有这么一个类,这个类继承自Activity,它叫ExpandableListActivity。顾名思义,从它的名字 可以看出该类是一种可扩展性的列表List,我们这里理解成可伸缩的列表,也就是通过继承ExpandableListActivity 可以实现列表的可展开/收缩的功能。
本文我们主要介绍这种列表的显示是如何实现的,在ListActivity的使用中,我们知道一旦继承了ListActivity,该类就意味这具备了 List的功能,同样的,我们将一个类继承了ExpandableListActivity,就可以直接调用该类本身的ExpandableList对 象,并直接赋予一个自定义的适配器setListAdapter(adapter);,因此,整个实现的重心放在如何设计这个适配器上面,以下是适配器的 一个举例。
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  //定义一个List,该List对象为一级条目提供数据
  List<Map<String, String>> groups = new ArrayList<Map<String, String>>();
  Map<String, String> group1 = new HashMap<String, String>();
  group1.put("group", "group1");
  Map<String, String> group2 = new HashMap<String, String>();
  group2.put("group", "group2");
  groups.add(group1);
  groups.add(group2);
  
  //定义一个List,该List对象为第一个一级条目提供二级条目的数据
  List<Map<String, String>> child1 = new ArrayList<Map<String, String>>();
  Map<String, String> child1Data1 = new HashMap<String, String>();
  child1Data1.put("child", "child1Data1");
  child1.add(child1Data1);
  Map<String,String> child1Data2 = new HashMap<String,String>();
  child1Data2.put("child", "child1Data2");
  child1.add(child1Data2);
  
  //定义一个List,该List对象为第二个一级条目提供二级条目的数据
  List<Map<String, String>> child2 = new ArrayList<Map<String, String>>();
  Map<String, String> child2Data = new HashMap<String, String>();
  child2Data.put("child", "child2Data");
  child2.add(child2Data);
  
  //定义一个List,该List对象用来存储所有的二级条目的数据
  List<List<Map<String, String>>> childs = new ArrayList<List<Map<String, String>>>();
  childs.add(child1);
  childs.add(child2);
  //生成一个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.groupTo }, childs, R.layout.child,
    new String[] { "child" }, new int[] { R.id.childTo });
  //将SimpleExpandableListAdapter对象设置给当前的ExpandableListActivity
  setListAdapter(sela);

原文地址:https://www.cnblogs.com/xingmeng/p/2419828.html