您的位置:首页 > 移动开发 > Android开发

android中ExpandableListView的使用

2016-10-15 17:49 295 查看
        看google官方BluetoothLeGatt代码时,碰到ExpandableListView,给它设置Adapter时使用的是SimpleExpandableListAdapter,设置的数据看的我是一脸懵逼,所以决定找个Demo理理思路。

       ExpandableListView是双层的ListView,所以设置数据的时候需要循环嵌套,外层循环设置一级数据,内层循环设置二级数据,一级数据就和普通的ListView的数据一样,需要一个ArrayList集合A去保存,二级数据本身就是一个ArrayList集合,它也需要一个ArrayList集合B去保存,且集合A的大小与集合B的大小相等。

     主要代码如下:

String[] names = {"腾讯","阿里","百度"};
String[][] childNames = {{"QQ","微信","管家"},{"支付宝","淘宝","优酷"},{"百度翻译","百度地图","百度一下"}};
List<HashMap<String,String>> companys = new ArrayList<> ();
ArrayList<ArrayList<HashMap<String,String>>>  products = new ArrayList<> ();

for (int i=0;i<names.length;i++){
HashMap<String,String> keyValue = new HashMap<> ();
keyValue.put ("name",names[i]);
keyValue.put ("id1",""+i);
companys.add (keyValue);
ArrayList<HashMap<String,String>> child = new ArrayList<> ();
for (int j=0;j<childNames[i].length;j++){
HashMap<String,String> producKeyValue = new HashMap<> ();
producKeyValue.put ("childName",childNames[i][j]);
producKeyValue.put ("id2",i+""+j);
child.add (producKeyValue);
}
products.add (child);
}
SimpleExpandableListAdapter adapter = new SimpleExpandableListAdapter (this,companys,
android.R.layout.simple_expandable_list_item_2,
new String[]{"name","id1"},
new int[]{android.R.id.text1,android.R.id.text2},
products,
android.R.layout.simple_expandable_list_item_2,
new String[]{"childName","id2"},
new int[]{android.R.id.text1,android.R.id.text2});

expandableListView.setAdapter (adapter);

     运行效果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: