我有以下代码令人惊讶地无法正常工作;

     needsInfoView = (ListView) findViewById(R.id.needsInfo);
            needsInfoList = new ArrayList<>();
            HashMap<String, String> needsInfoHashMap = new HashMap<>();

            for (int i = 0; i < 11; i++) {
                needsInfoHashMap.put("TA", needsTitleArray[i]);
                needsInfoHashMap.put("IA", needsInfoArray[i]);
                Log.e("NIMH",needsInfoHashMap.toString());
//Here, I get the perfect output - TA's value, then IA's value
                needsInfoList.add(needsInfoHashMap);
                Log.e("NIL",needsInfoList.toString());
//This is a mess - TA, IA values for 12 entries are all the same, they are the LAST entries of needsTitleArray and needsInfoArray on each ArrayList item.

                needsInfoAdapter = new SimpleAdapter(getBaseContext(), needsInfoList,
                        R.layout.needsinfocontent, new String[]{ "TA", "IA"},
                        new int[]{R.id.ta, R.id.ia});
                needsInfoView.setVerticalScrollBarEnabled(true);
                needsInfoView.setAdapter(needsInfoAdapter);
            }


请查看日志行下方的注释。那解释了我收到的输出。如何通过SimpleAdapter使ArrayList值传递到ListView中的两个文本字段?

谢谢

最佳答案

HashmapArrayList的for循环未保存正确的值


因为您要在HashMap中添加相同的实例needsInfoList

您需要在HashMap列表中添加新实例needsInfoList,如以下代码所示

另外,您需要在循环外将needsInfoAdapter设置为needsInfoView listview,如以下代码所示

尝试这个

needsInfoList = new ArrayList<>();
needsInfoView = (ListView) findViewById(R.id.needsInfo);

  for (int i = 0; i < 11; i++) {
       HashMap<String, String> needsInfoHashMap = new HashMap<>();
       needsInfoHashMap.put("TA", needsTitleArray[i]);
       needsInfoHashMap.put("IA", needsInfoArray[i]);
       needsInfoList.add(needsInfoHashMap);
   }
   needsInfoAdapter = new SimpleAdapter(getBaseContext(), needsInfoList,
                R.layout.needsinfocontent, new String[]{"TA", "IA"},
                new int[]{R.id.ta, R.id.ia});
   needsInfoView.setVerticalScrollBarEnabled(true);
   needsInfoView.setAdapter(needsInfoAdapter);

10-07 19:12
查看更多