2014-03-25 34 views
0

我有一个listView,我想打印包含所选项目的arrrayList。在Toast上显示ArrayList内容

我可以展示我每次选择的选择。即如果我选择了一个选项,我可以将其打印出来(我在代码中将其标记为注释),但我想将所有选项一起打印出来。 请帮忙吗?

谢谢..

+0

为什么你删除你以前发布的代码? – donfuxx

+0

@donfuxx如果你需要它,它存在于下面的答案 – user3287580

+0

我不明白你为什么删除了代码.. – donfuxx

回答

1

如果我理解正确的,你想显示在你的吐司的ArrayList的内容之间的逗号。

  1. 就像donfuxx说的,你需要在你的onclicklistener之外创建你的arrayList。
  2. 当用户点击一个项目时,它将被添加到你的arrayList中。
  3. 然后循环遍历该列表以填充名为allItems的字符串,然后在toast中显示allItems。

    ArrayList<String> checked = new ArrayList<String>(); 
    
    listView.setOnItemClickListener(new OnItemClickListener() { 
        @Override 
        public void onItemClick(AdapterView<?> parent, View view, 
          int position, long id) { 
    
         String listItem = (String) listView.getItemAtPosition(position); 
    
         if(!checked.contains(listItem)){ //optional: avoids duplicate Strings in your list 
          checked.add((position+1), listItem); 
         } 
         String allItems = ""; //used to display in the toast 
    
         for(String str : checked){ 
          allItems = allItems + "\n" + str; //adds a new line between items 
         } 
    
         Toast.makeText(getApplicationContext(),str, Toast.LENGTH_LONG).show(); 
        } 
    }); 
    
+0

您还应该确保避免IndexOutofBoundsException,因为您在ArrayList中可能不存在的位置添加项目。考虑使用checked.add(listItem)而不是checked.add((position + 1),listItem); –

0

那么你有正确的概念,在这里仅仅指刚执行错误是你错过了一部分:`

ArrayList<String> checked = new ArrayList<String>(); 
checked.add((position+1), listItem); 
Toast.makeText(getApplicationContext(),checked.get((position+1)), Toast.LENGTH_LONG).show();` 

你必须让ArrayList中元素的位置您需要如果你想显示每一个项目是在ArrayList中,你可以使用一个简单的循环,并将它们添加到像这样的字符串来获取,因此 checked.get(array position of element here)

0

... 
checked.add((position+1), listItem); 

String tempString = ""; 
for(int x = 0; x < checked.length(); x++) { 
    tempString = tempString + ", " + checked.get(x); 
} 
tempString = tempString.substring(2); 
Toast.makeText(getApplicationContext(),tempString, Toast.LENGTH_LONG).show(); 

编辑修改有点容下项目

+0

但我需要数组在其他地方使用它。 – user3287580

+0

这没有摆脱阵列,所以你可以在其他地方使用它。如果你想再次在一个字符串中的所有内容,只需再次运行循环或创建一个函数,将返回字符串。 – JStephen

+0

吐司不出现 – user3287580