ListView与多选

时间:2016-05-04 08:03:03

标签: android listview

   // **Step 1**: setAdapter to your listview.
   listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, GENRES));
   // **Step 2**:  set choice mode for listview .The second line of below code represents which checkbox should be checked.

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

    listView.setOnItemClickListener(this);



     private static  String[] GENRES = new String[] {
            "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
            "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
        };

    //**Step 3:** Checked views are returned in SparseBooleanArray, so you might use the below code to get key or values.The below sample are simply displayed selected names in a single String.
    @Override
    public void onItemClick(AdapterView<?> adapter, View arg1, int arg2, long arg3)
    {

    SparseBooleanArray sp=getListView().getCheckedItemPositions();

    String str="";
    for(int i=0;i<sp.size();i++)
    {
        str+=GENRES[sp.keyAt(i)]+",";
    }
    Toast.makeText(this, ""+str, Toast.LENGTH_SHORT).show();

    }

这对我有用。但是如果我将取消选中listitem如何从 str 中删除该项目。 STR + = GENRES [sp.keyAt(I)] +&#34;&#34 ;;

任何人都可以帮助我。

2 个答案:

答案 0 :(得分:0)

您似乎正在使用ListActivity,因为您调用了getListView()

如果是这种情况你应该使用

@Override
void onListItemClick(ListView l, View v, int position, long id) {
     // Handle SparseBooleanArray stuff.
}

另外,只需为SparseBooleanArray执行一个Log.d(),看看它是否返回了正确的值,或者在取消选中后ListView是否未正确更新。

答案 1 :(得分:0)

我得到了解决方案。

    String selected = ""; 
    int cntChoice = myList.getCount(); 
    SparseBooleanArray sparseBooleanArray =myList.getCheckedItemPositions();
     for(int i = 0; i < cntChoice; i++)
    { 
         if(sparseBooleanArray.get(i)) 
          { 
             selected += myList.getItemAtPosition(i).toString() + "\n";
          }
     } 

这对我有用。 :)