Adv

Kotlin Android – CheckBox Introduction

 

In this tutorial we introduce CheckBox, how to use it in android. Our programming language is Kotlin and our IDE is android studio.

 

Kotlin android checkbox

Kotlin android checkbox

1. build.gradle

In our app level build.gradle we make sure we have the Kotlin plugin in our dependencies closure.

implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

2. activity_main.xml

We add our CheckBox as well as our header label TextView here.

It is plain old XML for user interfaces even with Kotlin.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="info.camposha.kotlincheckboxes.MainActivity">

    <TextView
        android:id="@+id/headerLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="casual"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Mr. CheckBox"
        android:textAllCaps="true"
        android:textSize="24sp"
        android:textStyle="bold" />
    <CheckBox
        android:id="@+id/myCheckbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="CheckBox Unchecked"
        android:padding="5dp" />

</RelativeLayout>

3. MainActivity.java

Here’s our MainActivity.kt kotlin code.

package info.camposha.kotlincheckboxes

import android.app.Activity
import android.os.Bundle
import android.widget.CheckBox
import android.widget.CompoundButton

class MainActivity : Activity() {

    /*
    when activity is created
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //reference checkbox
        val myCheckBox = findViewById<CheckBox>(R.id.myCheckbox)
        //register event handler
        myCheckBox.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener {
            compoundButton, b -> myCheckBox.setText(if (compoundButton.isChecked) "CheckBox Checked" else "CheckBox Unchecked") })
    }
}

That’s it.

Share
Adv



Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )