In this short Kotlin programming tutorial we will learn how to create a Switch in Kotlin programmatically. In the code example below we are going to cover:
- Create Switch and add it to a LinearLayout
- Get input from the Switch when it’s state is changed
- Set textOff and textOn text programmatically
- Set OnClickListener on the Switch so that we can handle state changes event
Activity XML Layout File
Following is the Activity_switch_example.xml containing an empty LinearLayout to which we will add the Switch.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/linearLayout"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.appsdeveloperblog.kotlinexample3.SwitchExample">
</LinearLayout>
Switch UI Component Example in Kotlin
Below is Kotlin code example which demonstrates how to create and add a Switch UI component to our app activity programmatically. It also shows how to set onClickListener and handle events when user taps on the Switch component to change its state from On to Off and back from Off to On.
package com.appsdeveloperblog.kotlinexample3
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.Switch
class SwitchExample : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_switch_example)
val linearLayout = findViewById(R.id.linearLayout) as LinearLayout
val switch = Switch(this)
switch.textOn = "Switch is on"
switch.textOff = "Switch is off"
switch.text = "switch is "+ switch.isChecked
switch.setOnClickListener(View.OnClickListener {
switch.text = "switch is "+ switch.isChecked
})
linearLayout.addView(switch)
}
}
If you run the above code example in Android studio you should the the following view:

I hope this example was helpful!
If you are looking for more code examples in Kotlin or even longer step by step Kotlin tutorials, checkout the Android->Kotlin category of this blog.
And if you are looking for books or video tutorials on Kotlin check the list of resources below. I hope you will find some of them helpful!
Happy learning Kotlin!
Building Mobile Apps with Kotlin for Android – Books