1

If I have a ListView with the layout below where each item has a checkbox, how can I get all the checked items in the onClick() method when I click the Button?

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ListView
            android:id="@+id/listview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />

    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit"
        android:onClick="submitList"
        />

</RelativeLayout>

The onClick() method:

public void submitList(View view) {
    //
}

4 Answers4

1

You can check listview items one by one:

for ( int i=0; i < listview.getAdapter().getCount(); i++) {
listview.setItemChecked(i, true);
}
Shubhank Gupta
  • 833
  • 2
  • 15
  • 35
0

You can use SparseBooleanArray to get the checked items if you are using the ListView.CHOICE_MODE_MULTIPLE. Here is the reference of StackoverFlow question.

Community
  • 1
  • 1
Sanjeet A
  • 5,171
  • 3
  • 23
  • 40
0

You have to make one arraylist with size of your listview adapter. After that when you check any of your list item add that item in your array list.

public ArrayList<String> getCheckedName()
    {
        return array_list;
    }

Write this function in your adapter class. And when you want your checked data call

ArrayList<String> sName=adapter.getCheckedName();

Use this sName in your onClick method.

0
int len = listview.getCount();
SparseBooleanArray checked = listview.getCheckedItemPositions();
for (int i = 0; i < len; i++) {
    if (checked.get(i))
        String item = yourArrayList.get(i);
}
Ravi
  • 34,851
  • 21
  • 122
  • 183