我现在正在学习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个以上的项目。 Hardcoing显然不是正确的方法。因此,我希望用循环显示它们。
答案 0 :(得分:1)
假设您的数据是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()方法。