2013-06-18 26 views
0

我有一个ArrayList从onClick的几个按钮填充。我想弄清楚如何让我的ArrayList像项目一样组合成一个项目。用户按下按钮一次,“1无论”填充在列表中。如果他们再次按下相同的按钮,它会在列表中再次显示“1无论”,然后“1无论”。如果按钮被按下两次,如何让我的列表显示“2不管”?合并Like ArrayList中的项目

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)); 
     } 
    }); 
+0

Textwatcher..I打赌。只是不知道如何。 – SmulianJulian

+0

这些项目的格式始终为“item_count item_name”? –

+0

是的,总是一样的 – SmulianJulian

回答

1

我会强烈建议从项目名称,分离该项目计数,而不是一个字符串存储这两个值,并且使用自己的自定义对象适配器。这比使用字符串要容易得多。

不过,我认为这应该工作:

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()任何修改后,将其排序。

1

如果我理解正确,你有一个ArrayList,在其中添加少量按钮点击的项目,如果同一个按钮被点击两次或更多,你不想添加项目但增加列表中的项目数量。

为了解决这个问题,你可以定义一个项目类具有类成员的字符串,你可以用它来 识别物品和数量来跟踪点击次数

class Item 
{ 
String str; 
int count; 
} 

然后在每个按钮定义在将元素添加到ArrayList之前,如果它已经存在于列表中,则搜索字符串,如果发现字符串,则增加计数。