Android offers a wide variety of widgets for user interactions and CheckBox is one among them. CheckBox is a special kind of button with two states that can be either checked or unchecked. They serve as a simple tool to gather information from the user without much hassle. They are generally used to mark things as completed by the user in task management applications.
Some situations may arise where we might not know all the properties of the widget to be displayed at build-time and might have to dynamically assign those values. Thankfully, Android supports creating widgets at run-time. Let’s see how to create a CheckBox dynamically in Kotlin rather than at build-time.
Step 1: Creating a new project
To create a new project in android studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Modifying activity_main.xml
Before a CheckBox can be added dynamically, a layout needs to be defined beforehand to hold the CheckBox. To keep the application simple, choose a linear layout covering the entire screen for the demo application.
Step 3: Adding a string to strings.xml
It is best practice to not use hard-coded strings, and let’s do the same in the application.
This string can be referenced in the MainActivity.kt file using:
Step 4: Working with the MainActivity.kt file
Reference the layout from the MainActivity.kt file. This could be done using the following line of code:
val layout = findViewById<LinearLayout>(R.id.root_layout)
Now create a new CheckBox in the MainActivity.kt file and set its layout parameters. The layout parameters are compulsorily needed as they describe how the CheckBox will be interacting with the layout.
val geekBox = CheckBox(this)
geekBox.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
Set-up a listener to show a Toast message whenever the CheckBox is toggled by the user. Finally, add the created CheckBox to the layout using the below line of code.