0

I have a ListView with CheckBoxes as row elements (see the row layout below).

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <CheckBox
        android:id="@+id/delete_company_row_checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

How can I get a list of all rows with checked CheckBoxes (the user can select more than one list item) ?

Glory to Russia
  • 17,289
  • 56
  • 182
  • 325
  • 1
    You'll want to store the checked state in the data model that's backing your `ListView`. If it's a simple POJO, add an extra boolean field that you then toggle whenever the `CheckBox` changes its value. Alternatively, just add/remove the checked position to/from something like a `Set`, or use the platforms's built-in [`setItemChecked(int, boolean)`](http://developer.android.com/reference/android/widget/AbsListView.html#setItemChecked%28int,%20boolean%29). – MH. May 16 '13 at 19:17
  • @MH. Thanks. Can I add `android:choiceMode="multipleChoice"` to my `ListView` declaration in XML, iterate through all elements and use `ListView.isItemChecked` to determine whether a particular element is checked? – Glory to Russia May 17 '13 at 12:03
  • 1
    Yes, that's the gist of it. Alternatively you can get all checked positions by calling `getCheckedItemPositions()`. You may, however, not see the `CheckBox` automatically get checked/unchecked on tapping the row. You can either set the checked state manually or remove the wrapping `LinearLayout` so that your row layout end up being a 'checkable' widget. – MH. May 17 '13 at 22:47

1 Answers1

1

You can do something like this:

for (int i = 0; i < listview.getCount(); i++) {
    View view = listview.getChildAt(i);

    if ((CheckBox) view.findViewById(R.id.delete_company_row_checkbox)).isChecked()) {
        // Add what you need to a list or whatever you need. 
    }
}

Of course, it's a very basic example but the idea is to iterate through all of the listview child items and get the state of the checkboxes. Then if the state is checked - add the position or whatever you need to a list.

Seishin
  • 1,493
  • 1
  • 19
  • 30
  • 1
    You do know that a `ListView` recycles it views, right? In other words, what happens if you check the checkbox on the very first position, scroll down a bunch of items, and then try to get the view for that first position? Exactly. – MH. May 16 '13 at 19:13
  • Okay, then you can implement a ScrollListener. Something like this: http://stackoverflow.com/a/6384609/1281775 – Seishin May 16 '13 at 19:14