Create An Android Switch Programmatically in Kotlin




Target

Hello Readers! In this post, we are going to learn how to use android switch programmatically in kotlin any android application. We will also learn how to add switch in linearLayout programmatically in android application.

Output

Tutorialwing Android Dynamic Switch Output Android Switch programmatically in kotlin

Tutorialwing Android Dynamic Switch Output

Getting Started

At first, we will create android project. Then, we will create and use android switch programmatically in kotlin file.

1. Creating New Project in Kotlin

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

Step Description
1. Open Android Studio.
2. Go to File => New => New Project. Write application name as DynamicSwitch. 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. At this point, You will get a newly created android project successfully.

Now, we will modify xml and kotlin file to use android Switch dynamically.

2. Modify Values Folder

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

3. Modify Layout Folder

Open res/layout/activity_main.xml file. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	android:id="@+id/rootContainer"
	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">

</LinearLayout>

In activity_main.xml file, we have defined a linearLayout, with id rootContainer, that will act as container for the Switch widget created dynamically in the application.

4. Create Android Switch Programmatically / Dynamically in Kotlin

Open app/src/main/java/com.tutorialwing.dynamicswitch/MainActivity.kt file. Then, add below code into it.

package com.tutorialwing.dynamicswitch

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

class MainActivity : AppCompatActivity() {

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

        // Create Switch programmatically.
        val sw = Switch(this)
        val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        layoutParams.setMargins(30, 30, 30, 30)
        sw.layoutParams = layoutParams
        sw.text = "OFF"

        val linearLayout = findViewById<LinearLayout>(R.id.rootContainer)
        // Add Switch to LinearLayout
        linearLayout?.addView(sw)

        sw.setOnCheckedChangeListener { buttonView, 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 created Switch programmatically in kotlin in the application. Then, we have set layout params, margin and text to the Switch widget. At last, we have set checked change listener to show text as toast whenever there is change in the checked state of the Switch widget.

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

AndroidManifest.xml file

Code inside src/main/AndroidManifest.xml file is –

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.tutorialwing.dynamicswitch"
		  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 Creating Android Switch Programmatically in Kotlin.