Dynamic CheckBox in Android with Examples
Last Updated :
19 Feb, 2021
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
<?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"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
</LinearLayout>
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
<resources>
<string name="app_name">GFG | Dynamic Checkbox Demo</string>
<string name="geek_message">TODO: Become A Geek</string>
</resources>
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
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)
}
}
Output:
Similar Reads
CardView in Android With Example
CardView is a new widget in Android that can be used to display any sort of data by providing a rounded corner layout along with a specific elevation. CardView is the view that can display views on top of each other. The main usage of CardView is that it helps to give a rich feel and look to the UI
3 min read
Animation in Android with Example
Animation is the process of adding a motion effect to any view, image, or text. With the help of an animation, you can add motion or can change the shape of a specific view. Animation in Android is generally used to give your UI a rich look and feel. The animations are basically of three types as fo
7 min read
Dynamic Switch in Android
Switch is a widget used in android applications for performing two-state operations such as on or off. The switch provides functionality where the user can change the settings between on and off using the switch. In this article, we will take a look at How to Create a Switch dynamically in Android.
7 min read
Context Menu in Android with Example
In Android, there are three types of menus available to define a set of options and actions in the Android apps. Here in this article let's discuss the detail of the Context Menu. In Android, the context menu is like a floating menu and arises when the user has long-pressed or clicked on an item and
4 min read
ArrayAdapter in Android with Example
The Adapter acts as a bridge between the UI Component and the Data Source. It converts data from the data sources into view items that can be displayed into the UI Component. Data Source can be Arrays, HashMap, Database, etc. and UI Components can be ListView, GridView, Spinner, etc. ArrayAdapter is
3 min read
EditText widget in Android with Example
Widget refers to the elements of the UI (User Interface) that helps user interacts with the Android App. EditText is one of many such widgets which can be used to retrieve text data from user.EditText refers to the widget that displays an empty text field in which a user can enter the required text
4 min read
Input Events in Android with Example
In Android, there's quite a method to intercept the events from a user's interaction with your application. When considering events within your interface, the approach is to capture the events from the precise View object that the user interacts with. The View class provides the means to try to do s
7 min read
CustomArrayAdapter in Android with Example
In Android, ArrayAdapters are used for populating and controlling the ListView and Spinners. ArrayAdapter by default provides List-Items that include only single information or single TextView. In order to have a more complex layout that includes multiple information in a single List-Item such as im
6 min read
Modal Bottom Sheet in Android with Examples
In this article, we will learn about how to add Modal Bottom Sheet in our app. We have seen this UI component in daily applications like Google Drive, Maps, or Music Player App. The modal Bottom sheet always appears from the bottom of the screen and if the user clicks on the outside content then it
3 min read
Custom CheckBox in Android
CheckBox belongs to the android.widget.CheckBox class. Android CheckBox class is the subclass of CompoundButton class. It is generally used in a place where users can select one or more choices from a given list of choices. In this article, we are going to see how we can implement custom CheckBox in
3 min read