In this short Kotlin programming tutorial I am going to share with you how to create a CheckBox in Kotlin programmatically. You will learn how to create two checkboxes and how to read a value from CheckBox when it is selected. The code example below with cover:
- Create CheckBox in Kotlin programmatically,
- Use setOnClickListener to know when check state of CheckBox has changed,
- Read the value of CheckBox and display it in TextView
XML Layout File
<?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" android:id="@+id/constraintLayout" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.appsdeveloperblog.kotlinexample3.CheckBoxExample" android:orientation="vertical"> </LinearLayout>
CheckBox Example in Kotlin
In the code example below we will create two CheckBox(s) and will add then to our LinearLayout. We will check setOnClickListener on each CheckBox and will call the updateTextView() function when the OnClickListener event fires. Inside the updateTextView() function we will read the state value of each CheckBox and will print it out.
import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.constraint.ConstraintLayout import android.view.View import android.widget.CheckBox import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast class CheckBoxExample : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_check_box_example) val linearLayout = findViewById(R.id.constraintLayout) as LinearLayout val checkBox1 = CheckBox(this) checkBox1.text = "First CheckBox" checkBox1.isChecked = true val checkBox2 = CheckBox(this) checkBox2.text = "Second Checkbox" checkBox2.isChecked = false val textView = TextView(this) fun updateTextView() { textView.text = "checkBox1 is " + checkBox1.isChecked + " and checkBox2 is " + checkBox2.isChecked } updateTextView() checkBox1.setOnClickListener( View.OnClickListener { updateTextView() }) checkBox2.setOnClickListener( View.OnClickListener { updateTextView() }) linearLayout.addView(checkBox1) linearLayout.addView(checkBox2) linearLayout.addView(textView) } }
When you run this Kotlin code example, you should get the following view on your screen:
Don’t forget to check other Kotlin programming tutorials I have published in Kotlin category.
And if you are interested in learning Kotlin in more details, check out the below books and video lessons.
Happy learning Kotlin!
Happy learning Kotlin!
Building Mobile Apps with Kotlin for Android – Books