CheckBox | Android Studio | Kotlin
CheckBox | Android Studio | Kotlin
CheckBoxes are used to select one or more options from the available options. For example, you have a list of colors and the user can choose one or more colors from that list. We can use the CheckBox widget of android in such scenarios.
>>Watch For JavaStep 1: Create a new project or open an existing project
Step 2: Code
if (androidCb.isChecked) { //check box is checked } else { //check box is not checked or unchecked }
Add CheckedChange Listener on a CheckBox
androidCb.setOnCheckedChangeListener { _, isChecked -> //check if checkbox is checked or not if (isChecked) { //checkbox is checked } else { //checkbox is not checked } }
Complete Example
activity_main.xml<?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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp" tools:context=".MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Select Your Experiences:" android:textColor="#000" android:textStyle="bold" /> <CheckBox android:id="@+id/androidCb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="false" android:text="Android Developer" /> <CheckBox android:id="@+id/iosCb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="false" android:text="iOS Developer" /> <CheckBox android:id="@+id/graphicsCb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="false" android:text="Graphics Designer" /> <Button android:id="@+id/confirmBtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Confirm" /> <TextView android:id="@+id/resultTv" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
MainActivity.java
package com.blogspot.atifsoftwares.myapplication import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) confirmBtn.setOnClickListener { val result = StringBuilder() if (androidCb.isChecked) { result.append("\nAndroid Developer") } if (iosCb.isChecked) { result.append("\niOS Developer") } if (graphicsCb.isChecked) { result.append("\nGraphics Designer") } resultTv.text = "You're have selected:\n$result" } } }
Comments
Post a Comment