Showing an ArrayList content on a Toast

荒凉一梦 提交于 2019-12-12 01:34:18

问题


I have a listView and I want to print the arrrayList which contains the selected items.

I can show the choice that I choose every time. i.e. if I select a choice, I can print it in a toast (I mark it in my code as a comment), but I want to print the whole choices together. Any help please?

Thanks..


回答1:


If I understand correctly, you want to display the contents of your arrayList in a Toast.

  1. Like donfuxx said, you need to create your arrayList outside of your onclicklistener.
  2. As the user clicks an item, it will be added to your arrayList.
  3. Then loop over the list to fill a string called allItems, then show allItems in a toast.

    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();
        }
    });
    



回答2:


Well you have the right concept, jsut wrong execution here is the part you missed out on:`

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

You have to get the position of the element in the ArrayList which you require to fetch, hence checked.get(array position of element here)




回答3:


If you want to show every item that is in the ArrayList you can use a simple loop and add them to a string like this:

...
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 modified it a bit to only put commas between items



来源:https://stackoverflow.com/questions/22636941/showing-an-arraylist-content-on-a-toast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!