我有一个从onClick填充的几个按钮的ArrayList。我正在尝试弄清楚如何让我的ArrayList将相似的项目组合成一个项目。用户只需按一次按钮,列表中就会填充"1 list“。如果他们再次按下相同的按钮,它将在列表中再次显示"1 list“,然后再次显示"1 list”。如果按钮被按下两次,我如何让我的列表显示"2 List“?
ArrayList<String> listItems=new ArrayList<String>();
ArrayAdapter<String> adapter;
//Regular List
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,listItems);
setListAdapter(adapter);
//List From Another Activity
ArrayList<String> ai= new ArrayList<String>();
ai = getIntent().getExtras().getStringArrayList("list");
if (ai != null) {
listItems.add(ai+"");
adapter.notifyDataSetChanged();
}
//When the User pushes this button
//StackOverFlow help, Ignore this part if it's useless...wasnt sure
lay1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
listItems.add("1 "+stringm1a+" - "+intm1aa );
adapter.notifyDataSetChanged();
overallTotalproduct = intm1aa + overallTotalproduct;
textViewtotalproduct.setText(String.valueOf(overallTotalproduct));
}
});
发布于 2013-06-18 15:03:13
我强烈建议将条目计数与条目名称分开,而不是将这两个值都存储在一个字符串中,并使用您自己的自定义对象适配器。这将比使用Strings容易得多。
然而,我认为这应该是可行的:
String item = "1 Whatever";
// If the list contains this String
if (listItems.contains(item)) {
String[] words = item.split(" "); // Split the count and name
int count = Integer.parseInt(words[0]); // Parse the count into an int
count++; // Increment it
listItems.remove(item); // Remove the original item
listItems.add(count + " " + words[1]); // Add the new count + name eg "2 Whatever"
}
缺点是,这不会保持列表顺序,但在进行任何修改后,您始终可以使用Collections.sort()
对其进行排序。
发布于 2013-06-18 15:10:10
如果我理解正确的话,你有一个ArrayList,当点击几个按钮时,你可以添加项目,如果同一个按钮被点击两次或更多,你不想添加项目,而是增加列表中存在的项目的数量。
要解决此问题,您可以定义一个Item类,它具有类成员字符串(可用于标识项目)和一个用于跟踪点击量的计数
class Item
{
String str;
int count;
}
然后在每个按钮上定义字符串,在将元素添加到ArrayList之前,如果该字符串已存在于列表中,则搜索该字符串,如果找到该字符串,则增加计数
https://stackoverflow.com/questions/17161688
复制相似问题