ssummeraw 2013-08-01 08:32 采纳率: 10%
浏览 2200
已采纳

在 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));
        }
    });
  • 写回答

2条回答 默认 最新

  • markdowneide 2013-08-02 03:48
    关注

    我建议你从 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()来排序。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配