Create a Switch in Kotlin Programmatically

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=""

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.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.Switch

class SwitchExample : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        val linearLayout = findViewById( 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


If you run the above code example in Android studio you should the the following view:

Create Switch in Kotlin

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

Building Mobile Apps with Kotlin for Android – Video Courses

Leave a Reply

Your email address will not be published. Required fields are marked *