Sunday, 11 March 2018

Android Switch Widget Example Using Kotlin


1. Creating New Project in Kotlin
  • Open Android Studio.
  • Go to File => New => New Project.Give Name To your application. Then, check Include Kotlin Support and click next button.
  • Select minimum SDK you need. However, we have selected 21 as minimum SDK. Then, click next button.
  • Then, select Empty Activity => click next => click finish.
2. Here We Take Switch in our Layout . As in below xml layout.
main_activity.xml


<?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="com.dharmendra.aswitch.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="50dp"
        android:layout_marginTop="139dp"
        android:text="Switch :"
        android:textSize="20dp"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:id="@+id/textView" />

    <Switch
        android:id="@+id/sw"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/textView"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

3. MainActivity.kt

package com.dharmendra.aswitch

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Switch
import android.widget.Toast

class MainActivity : AppCompatActivity() {

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

        //Find View By Id for Switch

        val s=findViewById<Switch>(R.id.sw) as Switch

        //Onclik For Switch

        s.setOnClickListener {

            //To Chek Switch is On Or Off
            if(s.isChecked){
                Toast.makeText(this@MainActivity,"Switch is On",Toast.LENGTH_LONG).show()
            }

            else{
                Toast.makeText(this@MainActivity,"Switch is Off",Toast.LENGTH_LONG).show()
            }
        }
    }
}


Output:


No comments:

Post a Comment