Dynamic CheckBox in Android with Examples

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.

Approach

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.

XML

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
  
<!--This LinearLayout will serve as the root 
    container to hold the checkbox
    It will fully occupy the device screen and
    will place the checkbox at its center-->
<LinearLayout
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">
  
</LinearLayout>

chevron_right


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.

XML

filter_none

edit
close

play_arrow

link
brightness_4
code

<resources>
   <string name="app_name">GFG | Dynamic Checkbox Demo</string>
   <string name="geek_message">TODO: Become A Geek</string>
</resources>

chevron_right


This string can be referenced in the MainActivity.kt file using:

getString(R.string.geek_message)

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.

layout.addView(geekBox)

Kotlin

filter_none

edit
close

play_arrow

link
brightness_4
code

package org.geeksforgeeks.dynamic_checkbox
  
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.LinearLayout
import android.widget.Toast
  
class MainActivity : AppCompatActivity() {
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // References the root LinearLayout from 
        // the activity_main layout file
        val layout = findViewById<LinearLayout>(R.id.root_layout)
  
        // Create a new Checkbox at run-time
        val geekBox = CheckBox(this)
          
        // Define the layout properties and text for our check box
        geekBox.layoutParams = LinearLayout.LayoutParams(
          LinearLayout.LayoutParams.WRAP_CONTENT, 
          ViewGroup.LayoutParams.WRAP_CONTENT)
        geekBox.text = getString(R.string.geek_message)
          
        // Set-up a listener to show a Toast message when 
        // the check box is toggled.
        geekBox.setOnCheckedChangeListener{
          _, isChecked ->  Toast.makeText(this
                                          if (isChecked) "Congratulations!"
                                                          "You Are A Geek Now" 
                                          else "Don't Give Up"
                                          Toast.LENGTH_SHORT).show() }
  
        // Add our created check box to the root 
        // layout for it to be displayed
        layout.addView(geekBox)
    }   
}

chevron_right


Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.