Looking For Anything Specific?

[Tutorial][Part-1] How to Implement a Basic Checkbox in Android Kotlin With Sample Code Github

Hello Everyone,

In this post, I will be explaining how to use the checkbox in android with kotlin, so in a nutshell, a checkbox is nothing button with state handling with either it is selected or not. Unlike the radio button which is also servers the same purpose of handling the state of multiple buttons, we can choose any number of buttons state, wherein the radio button is used to select only one button state In a collection of buttons.

So what is checkbox? that my friend I have given a brief tutorial on the last post what I didn't give an explanation is how to make it as a custom one, Also I have shared an article on how can you make you android button a custom one at here [Tutorial] Android Button With Rounded Corner - Sample Code this little tutorial will teach you how to make a custom button. So let's get back here for the custom checkbox, like in the android button with rounded corner post we are going to use the help of drawable to make our android checkbox a custom one.


The general use case of a checkbox gives the user an ability to select more than one option at a time. Here is an image that gives you an idea about multiple checkboxes with its state.



In this tutorial, we are going to do exactly like this, and if you just want to take the code for references just go-ahead to the end of this post to grab the code from GitHub, Don't forget to share, Also we have some other posts that might interest you


How to create checkbox in android:

This is the part where you design the XML, Android natively supports the checkbox so you don't have to write any complex code to integrate it into your application Like I have mentioned in one of the earlier posts that we are going to be using the Constraint layout for android for most of the time in our tutorial, If you want to learn how to work with android constraint layout click here:
[Tutorial] Android Constraint Layout Example With Sample Code, this post will give a complete idea about constraint layout.  Let's get back here for the android checkbox tutorial.

    <CheckBox
        android:id="@+id/normalCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="Checkbox 1"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        app:layout_constraintBottom_toTopOf="@+id/customCheckBox"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Above is the code which is going to help us implement the checkbox in Android, let's take a look at this code in details so, all it has is a general id, height, width, and some basic stuff so nothing related to checkbox other than the root tag as CheckBox that's enough to make it as a checkbox. Below is the screenshot of how it will look in the layout editor. 

So this is a simple way to create an android checkbox, and now for the interesting part of handling the interaction on the checkbox, so if you read about our post on how to set on-click listener on the button we are going to do the same as those buttons we are going to set a click listener button in here it is a bit different that's because the CheckBox extends CompoundButton, so let's have a look at how to set a click listener on an android checkbox to handle its state

How to setOnCheckedChangeListener on to a CheckBox:

Yeah you read it right, it is onCheckedChangeListener in the checkbox, not onClickListener, so the rest is the same as for setting a setOnClickListener to a button, at first you have to get the reference of a button using findViewById like below code snippet

    private lateinit var checkBox1: CheckBox 
        checkBox1 = findViewById(R.id.normalCheckBox)

Once You got the reference to the android checkbox you can set a checked change listener to it. Like Below,

checkBox1.setOnCheckedChangeListener { _, isChecked ->
            if(isChecked){
                Toast.makeText(applicationContext,"Checkbox One Checked",Toast.LENGTH_SHORT).show()
            }else{
                Toast.makeText(applicationContext,"Checkbox One Unchecked",Toast.LENGTH_SHORT).show()
            }
        }

Above is the code that we are going to use to set on checked change listener to a checkbox in android which is the equivalent to android button's set on click listeners but not the same because in our android checkbox we have to know the state of the checkbox whether it is checked or not and the only way to do that is by adding the setOnCheckedChangeListener to it. So now let's take a look at this code in detail. And the output of the above code will look somewhat like this

how to setonclicklistener on android checkbox

If you want to learn how to make your checkbox like the custom one in the screenshot click here [Tutorial] Custom Checkbox Android With Sample Code Github

If you want to learn How to create custom checkbox like in the above picture, I will update them in a couple of days so stay tuned and Don't forget to follow me in social media Facebook Page  here and Twitter https://twitter.com/TutorialsMad

In the above code, we have used Kotlin's lambda function it is a simplified version of what we do for implementing a listener to button or any view. And if you notice closely that we have set the first parameter of this listener as "_" (underscore) which is not a mistake that it is the checkbox itself since we are not using it anywhere we have renamed it to "_" (underscore) as suggested by Kotlin in android studio. Now more about the code, as you can see this listener function accepts two parameters for this checkbox, the first parameter is the checkbox itself and the second parameter is the state of the button. And once you implement this listener to the android checkbox it will listener for change and will update the state of the button with the isChecked variable, So if click the button this listener will be triggered and the state of the button will be known from the isChecked variable, So to know what is happening we have used toast message to check the state of the checkbox this is one of the ways to test your application that getting feedback for action with toast, and if you don't know how to display toast message you can always read our tutorial here : [Tutorial] Show Toast Message Android Kotlin With Sample Code, once you have mastered the art of showing toast message form kotlin you can use that to check the state of your checkbox. Also, remember that it is not setOnClickListener which is for the android button that I have written a brief tutorial about here : [Tutorial] How To SetOnClickListener In Android Button Click With Kotlin, and for a checkbox it setOnCheckedChangeListener.

In case you missed:


Now that you have learned how to set on checked change listener onto an android checkbox you can now successfully create an application that can ask for a question and answer which supports multiple answers. But what if you have to check a button when you are starting an activity itself or let's say that you want to check a checkbox programmatically, Like when you want your user to select all check all checkboxes at once, Yeah this is one of the most useful use cases because I don't like to check more than two checkboxes.

How to check android checkbox programmatically in kotlin:

So in this section of the post, you will be learning how to change a checkboxes' checked state programmatically it is a simple process, actually, so there are two ways to do that, One is to define in XML and the other one is through programmatically with Kotlin. First, let's have a look at how can we achieve this case with XML

        android:checked="true"

Above is the attribute that you need to set the checkbox's checked state in the XML itself, so what it will do is it will create the view with the isChecked state as true if you listen for the change.

Secondly, if you want to change the state of a checkbox at runtime programmatically with kotlin you have to use the isChecked setter property on android checkbox like this,

        checkBox2.isChecked = true

The above code is the Kotlin's setter property the concept most of the java developers familiar with, so it is used to set a value, so if you click CTRL  + B on the property it will go to the function which will have the value which is actually returned from setChecked(), so like if you want to check a checkbox when a user clicks on another button you simply call this setter property with the state you want to change, It will set the state of the checkbox at runtime.

You can get the complete reference of android checkbox from here, Incase if I missed out something:https://developer.android.com/reference/kotlin/android/widget/CheckBox

Thanks for reading my article feel free to speak your mind. I have shared the code of this tutorial in my repository, You can get the complete code here,
Sample Code: Github Link

With this information this post is concluded , A Checkbox is a wonder-full choice if you want to provide user with multiple selections of potion to pick from or even a single one to act as a toggleable option,  You can learn on how to make your checkbox a custom in here Part 2 of this tutorial [Tutorial] [Part-2] Make Your Checkbox a Custom one In Android With Sample Code Github


In case you missed: