在 ArryList 中合并项目

通过点击一些按钮来生产一个 ArrayList。我想知道如何获取 ArrayList 来把items整合到一个item中。用户点击一次按钮,"1 whatever" 就会填充在list中,如果用户再次点击相同的按钮,"1 whatever"会再次出现在list中。如何让按钮点击两次时,让list显示 "2 whatever"?

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

我建议你从 item name 中分离 item count,而不是在一个字符串中存储两个值,使用自定义的 Object adapter,要比使用字符串简单。

String item = "1 Whatever";

// If the list contains this String
if (listItems.contains(item)) {
    String[] words = item.split(" ");        
    int count = Integer.parseInt(words[0]);  
    count++;                                 
    listItems.remove(item);                  
    listItems.add(count + " " + words[1]);   
}

缺点是不能保存列表顺序,但是你可以在任何修改后使用 Collections.sort()来排序。

没太搞明白 能详细的吗?

就是List.add()问题吗?