Tuesday, August 25, 2020

android kotlin - Material switch button

MainActivity.kt

package com.example.jetpack

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)


        // get the switch button initial on off status
        if (switchMaterial.isChecked)
        {
            textView.text = "Switch is initially on."
        }else{
            textView.text = "Switch is initially off."
        }


        // switch button checked change listener
        switchMaterial.setOnCheckedChangeListener { compoundButton, b ->
            if (b){
                // when checked
                textView.text = "Switch is on."
            }else{
                // if unchecked
                textView.text = "Switch is off."
            }
        }
    }
}
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">

    <com.google.android.material.switchmaterial.SwitchMaterial
        android:id="@+id/switchMaterial"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="On Off Me"
        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:gravity="center"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switchMaterial" />

</androidx.constraintlayout.widget.ConstraintLayout>
build.gradle(app) [dependency to add]

// material components theme
implementation 'com.google.android.material:material:1.2.0'