如何将ListText设置为ListView中的多个选定项目

时间:2015-02-28 14:50:39

标签: java android listview

有人可以告诉我如何在ListView中显示来自ListView的多个选定项目? 我想只显示所选项目,当项目未被选中时,它不能显示。 这是我的代码

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


}

2 个答案:

答案 0 :(得分:0)

  1. 每次调用onItemClick时,创建一个更新文本视图文本的方法。

    void updateTextView(){     ... }

  2. 使用getCheckedItemPositions获取列表中已检查项目的数组,并将其添加到您的方法中。 http://developer.android.com/reference/android/widget/AbsListView.html#getCheckedItemPositions()

  3. 使用StringBuilder为方法中的选定项添加标签:

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

答案 1 :(得分:-2)

Public void onItemClick(){
    String selectedItems="";
    SparseBooleanArray sparse=listview.getcheckedItemPositions();
    for(int i=0;i<adapterview.getCount();i++){
       if(sparse.get(i)){
          selectedItems+=adapterView.getItemAt(i).toString();
        }
    }
    Textview.setText("you selected"+selectedItems);
  }