【发布时间】:2018-07-25 18:53:36
【问题描述】:
我正在使用 listview 在我的 android 应用程序中添加列表。当我在 hashmap 中使用 for 循环时,它显示列表,但所有数据都在最终列表中,例如下面的代码工作正常。
products = new ArrayList<Cash>(products);
HashMap<String,String> temp=new HashMap<String, String>();
list=new ArrayList<HashMap<String,String>>();
temp.put("item1", "id1";
temp.put("item2", "name1");
temp.put("item3", "qty1");
temp.put("item4", "type1");
temp.put("item5", "quantity1");
temp.put("item6", "amt1");
list.add(temp);
temp1.put("item1", "id2";
temp1.put("item2", "name2");
temp1.put("item3", "qty2");
temp1.put("item4", "type2");
temp1.put("item5", "quantity2");
temp1.put("item6", "amt2");
list.add(temp1);
ListViewAdapters adapter1=new ListViewAdapters(getActivity(), list);
listView.setAdapter(adapter1);
它工作得很好,但是当我想使用 for 循环添加多个项目时。代码如下所示。 products 是包含项目的数组列表。
products = new ArrayList<Cash>(products);
HashMap<String,String> temp=new HashMap<String, String>();
list=new ArrayList<HashMap<String,String>>();
for (int i=0; i<products.size();i++){
Log.d("LOG","Product size:"+products.size());
Log.d("LOG","Product name:"+products.get(i).getName());
Log.d("LOG","Product amt:"+products.get(i).getAmount());
temp.put("item1", String.valueOf(i));
temp.put("item2", products.get(i).getName());
temp.put("item3", products.get(i).getQuantity());
temp.put("item4", products.get(i).getType());
temp.put("item5", products.get(i).getQuantity());
temp.put("item6", products.get(i).getAmount());
list.add(i, temp);
//list.
}
ListViewAdapters adapter1=new ListViewAdapters(getActivity(), list);
listView.setAdapter(adapter1);
我想要的输出
id1 名称1 数量1 类型1 数量1 amt1
id2 name2 qty2 type2 quantity2 amt2
但是得到输出是
id2 名称2 数量2 类型2 数量2 amt2
id2 name2 qty2 type2 quantity2 amt2
【问题讨论】:
-
它是更新而不是创建新的。在循环内使用
HashMap<String,String> temp=new HashMap<String, String>();
标签: java android listview arraylist hashmap