Today we will implement android checkbox in a ListView. If you haven’t yet implemented a ListView using Custom Adapter then refer here.

Android Checkbox

Below image shows the project structure of our android checkbox example application.

android-listview-checkboxes-project-structure-255x450

Android Checkbox example

The code for the activity_main.xml layout file is given below.

The layout for each row in the list is defined in row_item.xml as below.

The DataModel.java class for the ListView is defined as shown below.

The boolean parameter checked would be used for checking and unchecking checkboxes.

The MainActivity.java class file is given below.

In the above code, we set the ArrayList of DataModels object to the adapter. Whenever the ListView click listener is invoked we invert the checked value of the respective row and call notifyDataSetChanged() which updates the changes in the adapter class.

The CustomAdapter.java class file for the ListView is given below.

Let’s see the output when the above application is run.
android checkbox example, android checkbox listview

If you’ve followed so far and tried running the application you shall see that the clicking any rows doesn’t highlight it, neither does it change the check status. Only when you specifically click the checkbox it’s toggled. Our goal was to make checkboxes a part of the ListView row layout and not to let it behave independently. The reason for this conflict is:

Android CheckBox classes have their own set of click and check listeners. In order to avoid an interference between them and the ListView listener we’ve set the following attributes in the CheckBox widget in the xml.

  1. android:focusable="false"
  2. android:focusableInTouchMode="false"
  3. android:clickable="false"

These would make the CheckBoxes neither clickable nor focusable separately thereby letting the ListView row clicks function correctly.

The output of the application in action after doing the above fixes is given below.

android listview checkbox example

That’s all for android checkbox example with ListView. You can download the final android checkbox example project from below link.

Reference: Official Documentation

By admin

Leave a Reply