mardi 20 janvier 2015

Android checkbox issue in ListView

I have an issue with checkbox in ListView. What I wanna do is selecting multiple items and getting the selected items.


When I use CHOICE_MODE_MULTIPLE, I am able to get selected items but checkboxes are not working properly. For instance, I am selecting first item but second items is getting selected or I am deselecting second item but third item is getting selected etc.


When I use CHOICE_MODE_SINGLE, checkboxes are working properly but of course I am not able to get selected items. Here are my codes to select the checkboxes:



ListView listView = (ListView) findViewById(R.id.listChannels);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, arrChannelValues);
listView.setAdapter(adapter);
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckedTextView item = (CheckedTextView)view;
if(item.isChecked()){
item.setChecked(false);
}
else{
item.setChecked(true);
}
}
});


And my click event to get the selected items::



ListView listView = (ListView) findViewById(R.id.listChannels);
int cntChoice = listView.getCount();
String checked = "";
String unchecked = "";
SparseBooleanArray sparseBooleanArray = listView.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++)
{
if(sparseBooleanArray.get(i) == true)
{
checked += listView.getItemAtPosition(i).toString() + "\n";
}
else if(sparseBooleanArray.get(i) == false)
{
unchecked+= listView.getItemAtPosition(i).toString() + "\n";
}

}




Aucun commentaire:

Enregistrer un commentaire