Android Kotlin SwitchCompat (on/off) Button

A Switch is a two-state toggle switch widget that can select between two options. The user may drag the "thumb" back and forth to choose the selected option, or simply tap to toggle

SwitchCompat is a version of the Switch widget which runs on devices back to API 7.

Android Switch and ToggleButton both are the subclasses of CompoundButton class.

Lets see a sample example .

 XML Layout

  1. Create XML Layout activity_main.xml , this will be set as content view for launcher Activity (MainActivity.kt)
  2. Added Seekbar To the xml 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"
        android:layout_width="match_parent" android:layout_height="match_parent"
        tools:context=".MainActivity"
        android:padding="30dp"
        android:orientation="vertical"
        android:id="@+id/root">

    <androidx.appcompat.widget.SwitchCompat
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Swtich Button"
            android:id="@+id/switchCompat01"/>

</LinearLayout>

setOnCheckedChangeListener For Switch Button


setOnCheckedChangeListener is a callback that notifies swtich button is on /off

switchCompat01.setOnCheckedChangeListener { buttonView, isChecked ->
            val msg: String = if (isChecked)
                "Switch Button is Checked"
            else
                "Switch Button is UnChecked"
            showToast(msg)
        }

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 the setOnCheckedChangeListener for swtich and show the status  .

file : MainActivity.kt
package com.tutorialsbuzz.androidswtich

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)

        switchCompat01.setOnCheckedChangeListener { buttonView, isChecked ->
            val msg: String = if (isChecked)
                "Switch Button is Checked"
            else
                "Switch Button is UnChecked"
            showToast(msg)
        }
    }

    private fun showToast(msg: String) {
        Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
    }
}




No comments:

Post a comment