我有一个listView,我想打印包含选定项目的arrrayList。
我可以显示我每次选择的选择。即,如果我选择一个选项,则可以将其打印在烤面包上(我在代码中将其标记为注释),但是我想将所有选项一起打印。有什么帮助吗?
谢谢..
如果我理解正确,则想在Toast中显示arrayList的内容。
然后遍历列表以填充名为allItems的字符串,然后在烤面包中显示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(),allItems, Toast.LENGTH_LONG).show();
}
});
您有正确的概念,但这里错误的执行是您错过的部分:`
ArrayList<String> checked = new ArrayList<String>();
checked.add((position+1), listItem);
Toast.makeText(getApplicationContext(),checked.get((position+1)), Toast.LENGTH_LONG).show();`
您必须获取需要获取的ArrayList中元素的位置,因此checked.get(array position of element here)
如果要显示ArrayList中的每个项目,可以使用一个简单的循环并将它们添加到这样的字符串中:
...
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();
EDIT进行了一些修改,以仅在项目之间添加逗号