Android CheckBox with example

Android-CheckBox-with-example.png

21st February, 2023

CheckBox is a two-state button that can be either ON (checked) or OFF (unchecked) state. We will learn about Android checkbox in this tutorial.

1. Create CheckBox in Android Studio

We can create Android checkbox in two ways:

1.1 Create CheckBox in XML layout file

We know that we can design Android UI in XML layout file. So we can create a CheckBox using Android UI designer of Android Studio. Open the xml layout designer, select a checkbox from the palette, drag and drop it onto the layout design. Yeh.. Open the relevant Activity file, get a reference of the checkbox and do what you want to do.

XML
content_copy light_mode remove
<LinearLayout 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">
 
    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CheckBox1" />
 
</LinearLayout>

1.2 Create CheckBox Programmatically in Android

Another way, create an instance of the Android CheckBox class to programmatically create a checkbox . Use the instance based on your needs.

KotlinJava
content_copy light_mode remove
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val linearLayout = findViewById<LinearLayout>(R.id.linearLayout)

        //create checkbox programmatically
        val checkBox1 = CheckBox(this)
        //set attributes
        checkBox1.text = "Apple"
        checkBox1.setTextColor(Color.BLACK)

        //add checkbox to a layout
        linearLayout.addView(checkBox1)
    }
}
class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout linearLayout= findViewById(R.id.linearLayout);

        //create checkbox programmatically
        CheckBox checkBox1 = new CheckBox(this);
        //set attributes
        checkBox1.setText("Apple");
        checkBox1.setTextColor(Color.BLACK);

        //add checkbox to a layout
        linearLayout.addView(checkBox1);
    }
}

2. CheckBox Events

Some useful Android CheckBox events are listed below.

2.1 Android CheckBox Click Event Handling

2.1.1 CheckBox Click Event in layout file

Create a method in the Activity. The method must have View as parameter.

KotlinJava
content_copy light_mode remove
class MainActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        ...
        ...
    }
    fun onCheckBoxClicked(view: View) {
        if (view is CheckBox) {
            if (view.getId() == R.id.checkBox1) {
                Toast.makeText(this, "checkbox1 clicked", Toast.LENGTH_SHORT).show()
            }
        }
    }
}
class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ...
        ...
        ...
    }
 
    public void onCheckBoxClicked(View view) {
        if (view instanceof CheckBox) {
            if (view.getId() == R.id.checkBox1) {
                Toast.makeText(this, "checkbox1 clicked", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Open the xml layout file and set the method name as the value of the checkbox’s onClick attribute.

XML
content_copy light_mode remove
<LinearLayout 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=".MainActivity">
  
    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onCheckBoxClicked"
        android:text="CheckBox1" />
  
</LinearLayout>

2.1.2 CheckBox Click Event in Kotlin/Java file (Runtime click listener)

Alternatively, we can set a checkbox click listener in the Kotlin/Java activity. See the sample code below.

KotlinJava
content_copy light_mode remove
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //reference
        val checkBox1 = findViewById<CheckBox>(R.id.checkBox1)

        //click event
        checkBox1.setOnClickListener {
            Toast.makeText(this@MainActivity,"Checkbox 1 clicked",Toast.LENGTH_SHORT).show()
        }
    }
}
class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //reference
        CheckBox checkBox1 = findViewById(R.id.checkBox1);

        //click event
        checkBox1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "Checkbox 1 clicked", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

2.2 Android CheckBox Check Change Event Handling

This event is triggered when the state of the checkbox changes.

KotlinJava
content_copy light_mode remove
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //reference
        val checkBox1 = findViewById<CheckBox>(R.id.checkBox1)

        //click event
        checkBox1.setOnCheckedChangeListener(object : OnCheckedChangeListener {
            override fun onCheckedChanged(CompoundButton: CompoundButton?, isChecked: Boolean) {
                if (isChecked) {
                    Toast.makeText(this@MainActivity, "Checkbox1 checked", Toast.LENGTH_SHORT)
                        .show()
                } else {
                    Toast.makeText(this@MainActivity, "Checkbox1 unchecked", Toast.LENGTH_SHORT)
                        .show()
                }
            }
        })
    }
}
class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //reference
        CheckBox checkBox1 = findViewById(R.id.checkBox1);

        //check change event
        checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(MainActivity.this, "Checkbox1 checked", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Checkbox1 unchecked", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

3. CheckBox Attributes

Attribute Description
android:onClick Name of the method to invoke when the Checkbox clicked
android:checked It is used to specify the current state of the checkbox

4. Android CheckBox Example

This is a simple example where the user has to select the fruits he likes. When the user checks the checkbox, it will display a toast. Also when the user clicks the submit button, it will display the selected fruits.

Step 4.1: Create New Project

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from the templates.

Step 4.2: Enable View Binding

In this example we are using Android Jetpack’s feature view binding.

Groovy
content_copy light_mode remove
plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    ...
    ...

    buildFeatures {
        viewBinding = true
    }
    ...
    ...
}

dependencies {
    ...
    ...
    ...
}

Step 4.3: Add CheckBox to the XML Layout (UI)

Open the xml layout file and add a checkbox from the palette. Also add submit button. Set the onClick attribute in all checkboxes. If a checkbox is checked we will display a toast. See the code below.

XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Choose the fruits you like..."
        android:textSize="18sp" />

    <CheckBox
        android:id="@+id/appleCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onCheckBoxClicked"
        android:text="Apple" />

    <CheckBox
        android:id="@+id/bananaCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onCheckBoxClicked"
        android:text="Banana" />

    <CheckBox
        android:id="@+id/coconutCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onCheckBoxClicked"
        android:text="Coconut" />

    <CheckBox
        android:id="@+id/strawberryCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onCheckBoxClicked"
        android:text="Strawberry" />

    <Button
        android:id="@+id/submitButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:text="Submit" />

</LinearLayout>

Step 4.4: Update Activity File

Open the Activity file and create a method called onCheckBoxClicked. Also set click event on the submit button. The following code describes how it is.

KotlinJava
content_copy light_mode remove
package com.androidchunk.hellocheckbox

import android.os.Bundle
import android.view.View
import android.widget.CheckBox
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.androidchunk.hellocheckbox.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    //view binding
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.submitButton.setOnClickListener(View.OnClickListener {
            val stringBuilder = StringBuilder("You liked: ")
            if (binding.appleCheckBox.isChecked) {
                stringBuilder.append("\n")
                stringBuilder.append("Apple")
            }
            if (binding.bananaCheckBox.isChecked) {
                stringBuilder.append("\n")
                stringBuilder.append("Banana")
            }
            if (binding.coconutCheckBox.isChecked) {
                stringBuilder.append("\n")
                stringBuilder.append("Coconut")
            }
            if (binding.strawberryCheckBox.isChecked) {
                stringBuilder.append("\n")
                stringBuilder.append("Strawberry")
            }
            Toast.makeText(this@MainActivity, stringBuilder, Toast.LENGTH_SHORT).show()
        })
    }

    fun onCheckBoxClicked(view: View) {
        if (view is CheckBox && view.isChecked) {
            if (view.getId() == R.id.appleCheckBox) {
                Toast.makeText(this, "Apple selected", Toast.LENGTH_SHORT).show()
            } else if (view.getId() == R.id.bananaCheckBox) {
                Toast.makeText(this, "Banana selected", Toast.LENGTH_SHORT).show()
            } else if (view.getId() == R.id.coconutCheckBox) {
                Toast.makeText(this, "Coconut selected", Toast.LENGTH_SHORT).show()
            } else if (view.getId() == R.id.strawberryCheckBox) {
                Toast.makeText(this, "Strawberry selected", Toast.LENGTH_SHORT).show()
            }
        }
    }
}
package com.androidchunk.hellocheckbox;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.androidchunk.hellocheckbox.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    //view binding
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                StringBuilder stringBuilder = new StringBuilder("You liked: ");
                if (binding.appleCheckBox.isChecked()) {
                    stringBuilder.append("\n");
                    stringBuilder.append("Apple");
                }
                if (binding.bananaCheckBox.isChecked()) {
                    stringBuilder.append("\n");
                    stringBuilder.append("Banana");
                }
                if (binding.coconutCheckBox.isChecked()) {
                    stringBuilder.append("\n");
                    stringBuilder.append("Coconut");
                }
                if (binding.strawberryCheckBox.isChecked()) {
                    stringBuilder.append("\n");
                    stringBuilder.append("Strawberry");
                }
                Toast.makeText(MainActivity.this, stringBuilder, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void onCheckBoxClicked(View view) {
        if (view instanceof CheckBox && ((CheckBox) view).isChecked()) {
            if (view.getId() == R.id.appleCheckBox) {
                Toast.makeText(this, "Apple selected", Toast.LENGTH_SHORT).show();
            } else if (view.getId() == R.id.bananaCheckBox) {
                Toast.makeText(this, "Banana selected", Toast.LENGTH_SHORT).show();
            } else if (view.getId() == R.id.coconutCheckBox) {
                Toast.makeText(this, "Coconut selected", Toast.LENGTH_SHORT).show();
            } else if (view.getId() == R.id.strawberryCheckBox) {
                Toast.makeText(this, "Strawberry selected", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Run the application and check the output.

Step 4.5: Output

Happy coding!

Leave a Reply