CheckBox Tutorial and Example
CheckBox in Android.
CheckBox is a user interface element in Android which allows the user to select one or more options from a list of options. CheckBox is used when the user needs to select one or more options from a group of options. In this article, we will discuss how to use CheckBox in Android.
Step 1: Create a new Android Project
To use CheckBox in Android, we need to create a new Android project. Open Android Studio and click on "Start a new Android Studio project". Select "Empty Activity" and click on "Finish".
Step 2: Add CheckBox to the layout
Open the activity_main.xml file and add the following code to add a CheckBox to the layout.
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CheckBox"/>
In the above code, we have added a new CheckBox with id "checkBox" and text "CheckBox".
Step 3: Handle CheckBox events
In Android, we can handle CheckBox events using the setOnCheckedChangeListener() method. Add the following code to handle CheckBox events.
val checkBox = findViewById<CheckBox>(R.id.checkBox)
checkBox.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
// CheckBox is checked
} else {
// CheckBox is unchecked
}
}
In the above code, we have added a setOnCheckedChangeListener() method to the CheckBox. When the user checks or unchecks the CheckBox, the setOnCheckedChangeListener() method gets called and we can handle the CheckBox events accordingly.
Step 4: Get the state of CheckBox
To get the state of the CheckBox, we can use the isChecked property of the CheckBox. Add the following code to get the state of the CheckBox.
val checkBox = findViewById<CheckBox>(R.id.checkBox)
checkBox.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
// CheckBox is checked
} else {
// CheckBox is unchecked
}
}
val isChecked = checkBox.isChecked
In the above code, we have added a new variable isChecked to get the state of the CheckBox.
Step 5: Change the state of CheckBox programmatically
We can change the state of the CheckBox programmatically using the setChecked() method. Add the following code to change the state of the CheckBox programmatically.
val checkBox = findViewById<CheckBox>(R.id.checkBox)
checkBox.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
// CheckBox is checked
} else {
// CheckBox is unchecked
}
}
checkBox.isChecked = true
In the above code, we have changed the state of the CheckBox to checked using the setChecked() method.
More
A checkbox is a specific type of two-states button that can be either checked or unchecked.
Their primary role is to allow a user to select one or more option from a group of alternatives.
CheckBoxes are a popular way of representing Boolean values in Forms. Not only do they get used in mobile applications but also in desktop as well as online forms.
CheckBoxes, unlike RadioButtons, are managed independently of each other. Therefore each must handle its own events. This is because CheckBoxes, unlike RadioButtons, can be used to select many options, not just one.
A CheckBox is a CompoundButton in that it has two states. Also it does derive from the android.widget.CompoundButton class.
The CompoundButton is an abstract class defined in the android.widget package that acts as the interface definition for a callback to be invoked when the checked state of its child is changed.
The CompoundButton itself is a Button so CheckBox itself will inherit capabilities for Butttons.
CheckBox API Definition
The CheckBox resides in the android.widget namespace.
package android.widget;
It derives from android.widget.CompoundButton:
public class CheckBox extends android.widget.CompoundButton{}
Definition in XML Layout
CheckBoxes can be defined in the XML layouts like most widgets.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android_orientation="vertical"
android_layout_width="fill_parent"
android_layout_height="fill_parent">
<CheckBox android_id="@+id/checkbox_meat"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_text="@string/meat"
android_onClick="onCheckboxClicked"/>
<CheckBox android_id="@+id/checkbox_cheese"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_text="@string/cheese"
android_onClick="onCheckboxClicked"/>
</LinearLayout>
Manipulation From Java code.
Then CheckBox can be manipulated from the Java code.
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkbox_meat:
if (checked)
// blah blah
else
// blah blah
break;
case R.id.checkbox_cheese:
if (checked)
// blah blah
else
// blah blah
break;
}
}
Normally when a CheckBox is selected, the onClick event is raised. So in the above example, we defined an android:onClick attribute of our XML layout then registered it an event handler.
Example 1: Kotlin Android CheckBox Example
This is a simple checkbox example in kotlin android.
Step 1: Dependencies
No special dependency is needed for this project. However Kotlin and androidx are used.
Step2: Add to Layout
Next step is to add checkbox in your main activity layout as follows:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:layoutDirection="ltr"
android:textDirection="ltr">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:text="Which one do you know?"/>
<CheckBox
android:id="@+id/chk_main_java"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:text="Java"/>
<CheckBox
android:id="@+id/chk_main_kotlin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:text="Kotlin"/>
<Button
android:id="@+id/btn_main_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Result"
android:textAllCaps="false"
android:layout_marginTop="60dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:padding="10dp"/>
</LinearLayout>
Step 3: Write Kotlin Code
The last step is to write kotlin code. Below is the main activity showing how to do it:
MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn_main_result.setOnClickListener {
var name = ""
if (chk_main_java.isChecked) name += "Java "
if (chk_main_kotlin.isChecked) name += "Kotlin "
if(name.equals("")) Toast.makeText(applicationContext,"No Specialization",Toast.LENGTH_SHORT).show()
else Toast.makeText(applicationContext,"$name Programmer",Toast.LENGTH_SHORT).show()
}
}
}
Reference
Download the code below:
| No | Link |
|---|---|
| 1. | Download Code |
| 2. | Browse Code |
| 3. | Follow Code author |
Example 2
Let's now look at a full example in Java code. Here's the XML layout. We add a checkbox here.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
tools_context="info.camposha.mrcheckbox.MainActivity">
<TextView
android_id="@+id/headerLabel"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_fontFamily="casual"
android_layout_alignParentTop="true"
android_layout_centerHorizontal="true"
android_text="Mr. CheckBox"
android_textAllCaps="true"
android_textSize="24sp"
android_textStyle="bold" />
<CheckBox
android_id="@+id/myCheckbox"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_layout_centerInParent="true"
android_text="CheckBox Unchecked"
android_padding="5dp" />
</RelativeLayout>
Then here's our java code.
package info.camposha.mrcheckbox;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
public class MainActivity extends Activity {
/*
* When activity is Created.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//reference checkbox
final CheckBox myCheckBox = findViewById(R.id.myCheckbox);
//register event handler
myCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
myCheckBox.setText( compoundButton.isChecked() ? "CheckBox Checked" : "CheckBox Unchecked");
}
});
}
}
First we specify the package name to host our class.
Then add our imports using the
importdirective.Then create a public class we call
MainActivitythat derives fromandroid.app.Activity.We will then override the on
onCreate()method which is a life cycle callback for android. It gets called when the activity is created.Fist we invoke the
onCreate()method of the super class. That super class is the Activity. We pass it a bundle object.We invoke the
setContentView()which is a method inside theactivityclass and will inflate ourR.layout.activity_main.xmllayout and use it as the view for our main activity.First we reference the CheckBox using the
findViewByIdmethod, passing in the id from the layout.final CheckBox myCheckBox = findViewById(R.id.myCheckbox);We then attach our
onCheckedChangeListenerto our CheckBox. We override theonCheckedChange()callback.myCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
}
});Inside it we set text depending on whether the checkbox is selected or not.
myCheckBox.setText( compoundButton.isChecked() ? "CheckBox Checked" : "CheckBox Unchecked");
Kotlin Android CheckBox Examples
In this tutorial we introduce CheckBox, how to use it in android. Our programming language is Kotlin and our IDE is android studio.

Kotlin android checkbox
1. build.gradle
In our app level build.gradle we make sure we have the Kotlin plugin in our dependencies closure.
implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
2. activity_main.xml
We add our CheckBox as well as our header label TextView here.
It is plain old XML for user interfaces even with Kotlin.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.camposha.kotlincheckboxes.MainActivity">
<TextView
android:id="@+id/headerLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="casual"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Mr. CheckBox"
android:textAllCaps="true"
android:textSize="24sp"
android:textStyle="bold" />
<CheckBox
android:id="@+id/myCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="CheckBox Unchecked"
android:padding="5dp" />
</RelativeLayout>
3. MainActivity.java
Here's our MainActivity.kt kotlin code.
package info.camposha.kotlincheckboxes
import android.app.Activity
import android.os.Bundle
import android.widget.CheckBox
import android.widget.CompoundButton
class MainActivity : Activity() {
/*
when activity is created
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//reference checkbox
val myCheckBox = findViewById<CheckBox>(R.id.myCheckbox)
//register event handler
myCheckBox.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener {
compoundButton, b -> myCheckBox.setText(if (compoundButton.isChecked) "CheckBox Checked" else "CheckBox Unchecked") })
}
}
Conclusion
CheckBox is a simple and useful UI element in Android. In this article, we have discussed how to use CheckBox in Android. We have also provided some code examples to help you understand how to use CheckBox in your Android projects.
That's it. Best Regards.