我正在尝试从具有 1 个键的多个值的 HashMap 中检索数据并将其设置为 ListView ,但不是设置值 进入 ListView 并显示 ListView ,显示的只是数组(没有键)。 代码如下:
ListView lv = (ListView)findViewById(R.id.list);
//hashmap of type `HashMap<String, List<String>>`
HashMap<String, List<String>> hm = new HashMap<String, List<String>>();
List<String> values = new ArrayList<String>();
for (int i = 0; i < j; i++) {
values.add(value1);
values.add(value2);
hm.put(key, values);
}
并检索值并将其放入 ListView
ListAdapter adapter = new SimpleAdapter(
MainActivitty.this, Arrays.asList(hm),
R.layout.list_item, new String[] { key,
value1,value2},
new int[] { R.id.id, R.id.value1,R.id.value2 });
// updating listview
lv.setAdapter(adapter);
一个例子是 key=1,value2=2 和 value3=3,它将显示一个看起来像 [2,3] 的数组。 我如何让它显示 lisview 并添加 key ?
最佳答案
SimpleAdapters 构造函数将其声明为第二个参数:
data: A List of Maps. Each entry in the List corresponds to one row in the list. The Maps contain the data for each row, and should include all the entries specified in "from"
但是HashMap<String, List<String>>
hm 是列表的映射。就像List<Map<String,String>> hm
将是您可能需要的数据类型。
这是编辑后的来源:
ListView lv = (ListView)findViewById(R.id.list);
List<Map<String,String>> mapList = new ArrayList<Map<String, String>>();
Map<String,String> mapPerRow;
for (int i = 0; i < rowNumbers; i++) {
mapPerRow = new HashMap<String, String>();
mapPerRow.put("column1", value1);
mapPerRow.put("column2", value2);
mapList.add(mapPerRow);
}
ListAdapter adapter = new SimpleAdapter(
MainActivitty.this, mapList,
R.layout.list_item, new String[] { "column1", "colum2"},
new int[] { R.id.value1,R.id.value2 });
// updating listview
lv.setAdapter(adapter);
我不明白你为什么想要其中的 key (如果需要更多,只需将字符串添加到 map 中)?
关于java - HashMap 值未附加到 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17261990/