Saturday, February 10, 2018

android kotlin - ToggleButton example

MainActivity.kt

package com.cfsuman.kotlinexamples

import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.*
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Set an checked change listener for toggle button
        toggle_button.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                // The toggle is enabled/checked
                Toast.makeText(applicationContext,"Toggle on",Toast.LENGTH_SHORT).show()

                // Change the app background color
                root_layout.setBackgroundColor(Color.GREEN)
            } else {
                // The toggle is disabled
                Toast.makeText(applicationContext,"Toggle off",Toast.LENGTH_SHORT).show()

                // Set the app background color to gray
                root_layout.setBackgroundColor(Color.GRAY)
            }
        }


        // Set a click listener for root layout object
        root_layout.setOnClickListener{
            // Get the toggle button state programmatically
            if(toggle_button.isChecked){
                // If toggle button is checked/on then
                // The toggle is enabled/checked
                Toast.makeText(applicationContext,"Toggle on",Toast.LENGTH_SHORT).show()

                // Change the app background color
                root_layout.setBackgroundColor(Color.GREEN)
            }else{
                // The toggle is unchecked
                Toast.makeText(applicationContext,"Toggle off",Toast.LENGTH_SHORT).show()

                // Set the app background color to gray
                root_layout.setBackgroundColor(Color.GRAY)
            }
        }


        // Set a click listener for the button widget
        button.setOnClickListener{
            // Change the toggle button checked state on button click
            toggle_button.isChecked = if(toggle_button.isChecked)false else true
        }
    }
}
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:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    >
    <ToggleButton
        android:id="@+id/toggle_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Toggle State"
        />
</LinearLayout>