Android Switch Using Kotlin With Example




Target

Hello Readers! In this post, we are going to learn about android switch using kotlin in any android application. We will also go through different attributes of Switch widget that can be used to customise it.

Output

Tutorialwing Android Switch Output Android Switch Using Kotlin

Tutorialwing Android Switch Output

Getting Started

Android Switch can be defined as below –

Android Switch is a two-state toggle widget that can select between two options (ON or OFF). The user can drag and drop thumb to select between two options or it can simply tap to toggle the state.

Different Attributes of Android Switch Widget

Some of the popular attributes of Switch widget are –

Sr. XML Attributes Description
1 android:showText It is used to set whether we want to show text(ON/OFF) or not
2 android:textOff Specifies text to show when Switch is in OFF state.
3 android:textOn Specifies text to show when Switch is in ON state.
4 android:textStyle Sets style (bold, italic etc.) of the text.
5 android:thumb It is used to set drawable to be used as thumb that are moved back and forth.
6 android:thumbTextPadding It sets amount of padding on either side of text within the switch thumb.
7 android:thumbTint It is used to set tint to apply to the thumb
8 android:thumbTintMode It is used to set blending mode used to apply the thumb tint
9 android:track It is used to set drawable of the track in which thumb slides back and forth
10 android:typeface Specifies typeface for the text. For example, normal, sans, serif, monospace etc.

Some of the popular attributes of android Switch widget inherited from Compound Button are –

Sr. XML Attributes Description
1 android:button It is used to set drawable to button
2 android:buttonTint It is used to set tint to apply to button tint
3 android:buttonTintMode It is used to set blending mode used to apply to button graphic tint

Some of the popular attributes of android Switch inherited from TextView are –

Sr. XML Attributes Description
1 android:autoLink It is used to decide whether text such as email, url should be automatically detected and converted into links or not.
2 android:cursorVisible It is used to decide whether cursor should be visible or not.
3 android:drawableBottom It is used to set drawable to be shown below text
4 android:ems It is used to set the view be exactly this ems wide

Some of the popular attributes of android Switch inherited from View are –

Sr. XML Attributes Description
1 android:background Sets background
2 android:clickable Decides whether view is clickable or not
3 android:focusable Controls whether a view can take focus or not
4 android:id Id of the view



Example of Android Switch Using Kotlin

At first, we will create android application. Then, we will use switch widget in the application.

1. Creating New Project in Kotlin

Follow steps below to create new project. Please ignore the steps if you have already created the project.

Step Description
1. Open Android Studio.
2. Go to File => New => New Project. Write application name as Switch. Then, check Include Kotlin Support and click next button.
3. Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button
4. Then, select Empty Activity => click next => click finish.
5. You will get a newly created project successfully if you have followed steps properly.

Since we have a new application, we will modify xml and other file to use switch using kotlin in the application.

2. Modify values folder

No values folders have been modified. So, we are not going to mention them here.

3. Use Switch Widget in xml file

Open src/main/res/layout/activity_main.xml file and add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:gravity="center"
	android:orientation="vertical">

	<Switch
		android:id="@+id/switch1"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="OFF"/>

</LinearLayout>

In activity_main.xml file, we have defined Switch widget. Now, we will access this Switch using kotlin file in the application.

4. Access Switch Using Kotlin file

Open src/main/java/com.tutorialwing.aswitch/MainActivity.kt file and add below code into it.

package com.tutorialwing.aswitch

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

class MainActivity : AppCompatActivity() {

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

        val sw = findViewById<Switch>(R.id.switch1)
        sw?.setOnCheckedChangeListener({ _, isChecked ->
            val msg = if (isChecked) "ON" else "OFF"
            Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
            sw.text = msg
        })
    }
}

In MainActivity.kt file, we have accessed Switch widget defined in xml file. Then, we have set a checked change listener to show a toast message whenever checked state is changed.

Since AndroidManifest.xml file is very important in android application, we are also going to see the content inside this file.

AndroidManifest.xml file

Code inside main/AndroidManifest.xml file is as below.

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.tutorialwing.aswitch"
		  xmlns:android="http://schemas.android.com/apk/res/android">

	<application
		android:allowBackup="true"
		android:icon="@mipmap/ic_launcher"
		android:label="@string/app_name"
		android:roundIcon="@mipmap/ic_launcher_round"
		android:supportsRtl="true"
		android:theme="@style/AppTheme">
		<activity android:name=".MainActivity">
			<intent-filter>
				<action android:name="android.intent.action.MAIN"/>

				<category android:name="android.intent.category.LAUNCHER"/>
			</intent-filter>
		</activity>
	</application>

</manifest>

When we run the program, we will get output as shown above.

That’s end of our tutorial on Android Switch using Kotlin.