首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在ArrayList中合并类似项

在ArrayList中合并类似项
EN

Stack Overflow用户
提问于 2013-06-18 14:11:24
回答 2查看 524关注 0票数 0

我有一个从onClick填充的几个按钮的ArrayList。我正在尝试弄清楚如何让我的ArrayList将相似的项目组合成一个项目。用户只需按一次按钮,列表中就会填充"1 list“。如果他们再次按下相同的按钮,它将在列表中再次显示"1 list“,然后再次显示"1 list”。如果按钮被按下两次,我如何让我的列表显示"2 List“?

代码语言:javascript
运行
复制
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));
        }
    });
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-06-18 15:03:13

我强烈建议将条目计数与条目名称分开,而不是将这两个值都存储在一个字符串中,并使用您自己的自定义对象适配器。这将比使用Strings容易得多。

然而,我认为这应该是可行的:

代码语言:javascript
运行
复制
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
EN

Stack Overflow用户

发布于 2013-06-18 15:10:10

如果我理解正确的话,你有一个ArrayList,当点击几个按钮时,你可以添加项目,如果同一个按钮被点击两次或更多,你不想添加项目,而是增加列表中存在的项目的数量。

要解决此问题,您可以定义一个Item类,它具有类成员字符串(可用于标识项目)和一个用于跟踪点击量的计数

代码语言:javascript
运行
复制
class Item
{
String str;
int count; 
}

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17161688

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档