Android CheckBox

Filed Under: Android

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 checkbox example

Android Checkbox example

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


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.journaldev.listviewwithcheckboxes.MainActivity">

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

</android.support.constraint.ConstraintLayout>

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


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

    <TextView
        android:id="@+id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:textSize="16sp" />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />


</RelativeLayout>

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


package com.journaldev.listviewwithcheckboxes;

public class DataModel {

    public String name;
    boolean checked;

    DataModel(String name, boolean checked) {
        this.name = name;
        this.checked = checked;

    }
}

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

The MainActivity.java class file is given below.


package com.journaldev.listviewwithcheckboxes;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList dataModels;
    ListView listView;
    private CustomAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        listView = (ListView) findViewById(R.id.listView);

        dataModels = new ArrayList();

        dataModels.add(new DataModel("Apple Pie", false));
        dataModels.add(new DataModel("Banana Bread", false));
        dataModels.add(new DataModel("Cupcake", false));
        dataModels.add(new DataModel("Donut", true));
        dataModels.add(new DataModel("Eclair", true));
        dataModels.add(new DataModel("Froyo", true));
        dataModels.add(new DataModel("Gingerbread", true));
        dataModels.add(new DataModel("Honeycomb", false));
        dataModels.add(new DataModel("Ice Cream Sandwich", false));
        dataModels.add(new DataModel("Jelly Bean", false));
        dataModels.add(new DataModel("Kitkat", false));
        dataModels.add(new DataModel("Lollipop", false));
        dataModels.add(new DataModel("Marshmallow", false));
        dataModels.add(new DataModel("Nougat", false));

        adapter = new CustomAdapter(dataModels, getApplicationContext());

        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {

                DataModel dataModel= dataModels.get(position);
                dataModel.checked = !dataModel.checked;
                adapter.notifyDataSetChanged();


            }
        });
    }
}

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.


package com.journaldev.listviewwithcheckboxes;

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import java.util.ArrayList;

public class CustomAdapter extends ArrayAdapter {

    private ArrayList dataSet;
    Context mContext;

    // View lookup cache
    private static class ViewHolder {
        TextView txtName;
        CheckBox checkBox;
    }

    public CustomAdapter(ArrayList data, Context context) {
        super(context, R.layout.row_item, data);
        this.dataSet = data;
        this.mContext = context;

    }
    @Override
    public int getCount() {
        return dataSet.size();
    }

    @Override
    public DataModel getItem(int position) {
        return dataSet.get(position);
    }


    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {

        ViewHolder viewHolder;
        final View result;

        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item, parent, false);
            viewHolder.txtName = (TextView) convertView.findViewById(R.id.txtName);
            viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);

            result=convertView;
            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
            result=convertView;
        }

        DataModel item = getItem(position);


        viewHolder.txtName.setText(item.name);
        viewHolder.checkBox.setChecked(item.checked);


        return result;
    }
}

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.


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

    <TextView
        android:id="@+id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:textSize="16sp" />

    <CheckBox
        android:id="@+id/checkBox"
        android:clickable="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:focusable="false"
        android:focusableInTouchMode="false" />


</RelativeLayout>

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

Comments

  1. Gunjan says:

    Hello
    I want to send the selected item to the server .
    How can i do that ???
    How to extract the value of selected item and send them to the server on a button click please help

  2. Premkumar says:

    Hi
    I am using this tutorial and i got one error message for customAdapter. java file. how to resolve this error?

    @Override
    public DataModel getItem(int position) {
    return dataSet.get(position);
    }

  3. YP says:

    Hi

    I’m using your tutorial to learn about ListView however I keep getting two errors.

    In CustomAdapter.java at:

    @Override
    public DataModel getItem(int position) {
    return dataSet.get(position); //ERROR HERE
    }

    I get the error for incompatible types.

    In MainActivity.java at:
    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {

    DataModel dataModel= dataModels.get(position); //ERROR HERE
    dataModel.checked = !dataModel.checked;
    adapter.notifyDataSetChanged();
    }
    });

    I get the same error.

    Android Studio is telling me to cast both. This resolves the error messages but when I run the app I only see the first item in the listview.

    1. M.Tamilselvan says:

      DataModel dataModel= (LVwithCheckBox_DataModel) dataModels.get(position);

      // typecast

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages