Switch button listener Kotlin Android

Android code switch button for androidSwitch is a two-state user interface element that is used to display ON (Checked) or OFF (Unchecked) states as a button with thumb slider. By using thumb, the user may drag back and forth to choose an option either ON or OFF .

Example with reverse text show using switch button listener

MainActivity.kt

package com.jigopost.switchbutton

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)

        // text to reverse
        val text = "ANDROID DEVELOPERS"

        // switch button checked change listener
        switchButton.setOnCheckedChangeListener { compoundButton, b ->
            if (b){
                // when switch button is checked
                textView.text = "Switch is on."
                textView.append("\n\n${text.reversed()}")
            }else{
                // if switch button is unchecked
                textView.text = "Switch is off."
                textView.append("\n\n$text")
            }
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EDEAE0"
    tools:context=".MainActivity">

    <Switch
        android:id="@+id/switchButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Reverse Text"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.25" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif-condensed-medium"
        android:padding="8dp"
        tools:text="TextView"
        android:textColor="#1034A6"
        android:gravity="center"
        android:textSize="30sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switchButton" />

</androidx.constraintlayout.widget.ConstraintLayout>

Output

Leave a Reply