How to setext to multiple selected items from a ListView

advertisements

Can somebody tell me how can I display in a TextView multiple selected items from a ListView? I want to display only items which are selected, when item is unselected it can't be displayed. Here's my code

final String[] favoriteTVShows =
            {
                    "Wolf", "Inception", "Heat", "Gladiator", "Birdman", "Seven", "TVshow1", "TVshow2", "Tvshow3"
            };

    ListAdapter theAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, favoriteTVShows);

    ListView theListView = (ListView) findViewById(R.id.theListView);

    theListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    theListView.setItemChecked(2, true);

    theListView.setAdapter(theAdapter);

    theListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            String tvShowPicked = "You selected " + String.valueOf(adapterView.getItemAtPosition(position));

            Toast.makeText(List.this, tvShowPicked, Toast.LENGTH_SHORT).show();
        }
    });

}


  1. Create a method to update the text view text every time onItemClick is called.

    void updateTextView() { ... }

  2. Use getCheckedItemPositions to get an array of checked items in your list and add it your method. http://developer.android.com/reference/android/widget/AbsListView.html#getCheckedItemPositions()

  3. Use a StringBuilder to add the labels for selected items inside the method:

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < selectedItems; i++) {
        sb.append(selectedItems[i]);
        if (i < selectedItems.length - 1) {
            sb.append(", "); // Add a comma for separation
        }
    }
    textView.setText(sb);