我有一個listView,我想打印包含所選項目的arrrayList。在Toast上顯示ArrayList內容
我可以展示我每次選擇的選擇。即如果我選擇了一個選項,我可以將其打印出來(我在代碼中將其標記爲註釋),但我想將所有選項一起打印出來。 請幫忙嗎?
謝謝..
我有一個listView,我想打印包含所選項目的arrrayList。在Toast上顯示ArrayList內容
我可以展示我每次選擇的選擇。即如果我選擇了一個選項,我可以將其打印出來(我在代碼中將其標記爲註釋),但我想將所有選項一起打印出來。 請幫忙嗎?
謝謝..
如果我理解正確的,你想顯示在你的吐司的ArrayList的內容之間的逗號。
然後循環遍歷該列表以填充名爲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();
}
});
您還應該確保避免IndexOutofBoundsException,因爲您在ArrayList中可能不存在的位置添加項目。考慮使用checked.add(listItem)而不是checked.add((position + 1),listItem); –
那麼你有正確的概念,在這裏僅僅指剛執行錯誤是你錯過了一部分:`
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)
:
...
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();
編輯修改有點容下項目
但我需要數組在其他地方使用它。 – user3287580
這沒有擺脫陣列,所以你可以在其他地方使用它。如果你想再次在一個字符串中的所有內容,只需再次運行循環或創建一個函數,將返回字符串。 – JStephen
吐司不出現 – user3287580
爲什麼你刪除你以前發佈的代碼? – donfuxx
@donfuxx如果你需要它,它存在於下面的答案 – user3287580
我不明白你爲什麼刪除了代碼.. – donfuxx