我现在正在学习ExpandableListview。到目前为止,我设法以硬编码方式显示父数据和子数据。
但是,我需要从数据库中获取数据,然后动态地显示它们。
看起来这与For循环和内部For循环有关。但我一直在想这个结构但失败了。有人能帮忙吗?
adapter adapter; // BaseExpandableListAdapter
ExpandableListView expandableListView;
List<String> category;
HashMap<String,List<String>> item;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ex_listview);
expandableListView=(ExpandableListView)findViewById(R.id.listview);
display();
adapter=new adapter(this,category,item);
expandableListView.setAdapter(adapter);
}
public void display(){
category=new ArrayList<String>();
item=new HashMap<String,List<String>>();
category.add("Western Food");
category.add("Chinese Food");
category.add("Japanese Food");
List<String> western_food = new ArrayList<String>();
western_food.add("Fried Chicken");
western_food.add("French Fries");
western_food.add("Beef Steak");
List<String> chinese_food = new ArrayList<String>();
chinese_food.add("Chicken Rice");
chinese_food.add("Duck Rice");
List<String> japanese_food = new ArrayList<String>();
japanese_food.add("Tapanyaki");
japanese_food.add("Takoyagi");
japanese_food.add("Sushi");
japanese_food.add("Lamian");
item.put(category.get(0), western_food);
item.put(category.get(1), chinese_food);
item.put(category.get(2), japanese_food);
}
结果的截图
假设数据库有10个类别,每个类别都有超过10个项。显然,硬道理并不是正确的方法。因此,我希望用循环来显示它们。
发布于 2016-10-11 09:35:01
假设您的数据是JSON格式的,它包含一个类别数组,并且每个类别都有一个条目数组,这使得示例数据看起来像
"categories": [
{
"name": "category1",
"items": [
"item1",
"item2",
"item3"
]
},
{
"name": "category2",
"items": [
"item1",
"item2",
"item3",
"item4"
]
},
{
"name": "category3",
"items": [
"item1",
"item2"
]
}
]
您可以使用for循环解析JSON数据,在相同的for循环中,您可以向可扩展视图添加元素,如下所示
category=new ArrayList<String>();
item=new HashMap<String,List<String>>();
JSONArray categoryList = new JSONArray(yourJsonData);
for(int i=0; i < categoryList.length(); i++){
JSONObject category = categoryList.get(i);
String categoryName = category.getString("name");
JSONArray itemArray = category.getJSONArray("items");
List<String> foods = new ArrayList<String>();
for(int j=0; j<itemArray.length(); j++){
foods.add(itemArray.get(j));
}
item.put(categoryName,foods);
}
上面的循环可以对任意大小的数据替换display()方法。
https://stackoverflow.com/questions/39978005
复制