Android CheckBox Widget Kotlin

Android CheckBox class is the subclass of CompoundButton class. , Android CheckBox Allows User to Select one or More options from a set .

1. XML Layout

  1. Create XML Layout activity_main.xml , this will be set as content view for launcher Activity (MainActivity.kt) .
  2. Add CheckBox to the layout .
file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="50dp"
        tools:context=".MainActivity"
        android:id="@+id/root">

    <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/checkbox01"
            android:text="checkbox 01"
            android:padding="10dp"
            android:textSize="16sp"
            android:textColor="#000"/>

    <CheckBox android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/checkbox02"
              android:text="checkbox 02"
              android:padding="10dp"
              android:textSize="16sp"/>

</LinearLayout>

2. OnCheckedChangeListener


Set setOnCheckedChangeListener for checkBox , show toast message with checked/un-checkBox status .

checkbox01.setOnCheckedChangeListener({ buttonView, isChecked ->
 Toast.makeText(this@MainActivity, buttonView.text.toString()+ ": " + isChecked, Toast.LENGTH_SHORT).show()
})


3. Activity


  1. Create a koltin class MainActivity.kt and extend it to AppCompatActivity class .
  2. Override onCreate function and set the content of this MainActivity with above defined xml layout (activity_main.xml).
  3. Set setOnCheckedChangeListener for checkBox , show toast message with checked/un-checkBox status .

file : MainActivity.kt
package com.tutorialsbuzz.androidcheckbox

import android.os.Bundle
import android.widget.Toast
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)

        checkbox01.setOnCheckedChangeListener({ buttonView, isChecked ->
            Toast.makeText(this@MainActivity, buttonView.text.toString()+ ": " + isChecked, Toast.LENGTH_SHORT).show()
        })

        checkbox02.setOnCheckedChangeListener({ buttonView, isChecked ->
            Toast.makeText(this@MainActivity, buttonView.text.toString()+ ": " + isChecked, Toast.LENGTH_SHORT).show()
        })
    }
}



No comments:

Post a Comment