I've a couple of question I haven't been able to figure out.
I'm trying to get all the checked elements from a ListView
but:
If I check and then uncheck an element, it's returned as "checked" by the getCheckedItemPositions()
function
I don't know how can I iterate through this:
SparseBooleanArray checked = list.getCheckedItemPositions();
The other answers using SparseBooleanArray
are nearly correct, but they are missing one important thing: SparseBooleanArray.size()
will sometimes only return the count of true
values. A correct implementation that iterates over all the items of the list is:
SparseBooleanArray checked = list.getCheckedItemPositions(); for (int i = 0; i < list.getAdapter().getCount(); i++) { if (checked.get(i)) { // Do something } }
I solved my case with this:
public class MyAdapter extends BaseAdapter{ public HashMap<String,String> checked = new HashMap<String,String>(); .... public void setCheckedItem(int item) { if (checked.containsKey(String.valueOf(item))){ checked.remove(String.valueOf(item)); } else { checked.put(String.valueOf(item), String.valueOf(item)); } } public HashMap<String, String> getCheckedItems(){ return checked; } }
To set an element is checked:
public class FileBrowser extends Activity implements OnClickListener{ private ListView list; ... list.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int item, long id) { BrowserAdapter bla = (BrowserAdapter) parent.getAdapter(); bla.setCheckedItem(item); } });
Then to get the checked items from outside the class..
MyAdapter bAdapter; Iterator<String> it = bAdapter.getCheckedItems().values().iterator(); for (int i=0;i<bAdapter.getCheckedItems().size();i++){ //Do whatever bAdapter.getItem(Integer.parseInt(it.next()); }
Hope it can help someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With