java - HashMap 值未附加到 ListView

标签 java android dictionary hashmap

我正在尝试从具有 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/

相关文章:

java - ImageView隐藏父级的圆角

android - 与 Android 的持续集成 [Codeship]

java - 使用 Intent 打开 Waze GPS 导航或谷歌地图

python-3.x - 在数据框中包含使用 MAP 和字典的列

c# - JAVA `System.exit(0);` 的 C# 等效项是什么?

java - 如何从 Collection 中返回 N 个连续的元素?

java - 隐式 QueryStringBindable java.util.List[models.InputTimeSheetDataStore]

java - 用于 XML 解析的 Android SimpleXML 库

android - 使用库项目和 android.view.InflateException 二进制 XML 文件行 #7 错误膨胀类

c++ - 访问 map 元素