Switch is a widget used in android applications for performing two-state operations such as on or off. The switch provides functionality where the user can change the settings between on and off using the switch. In this article, we will take a look at How to Create a Switch dynamically in Android. A sample video is given below to get an idea about what we are going to do in this article.
Note: This Android article covered in both Java and Kotlin languages.Â
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Working with the activity_main.xml file
Navigate to app > res > layout > activity_main.xml and add the below code to it. Comments are added in the code to get to know in detail.Â
XML
<?xml version="1.0" encoding="utf-8"?><!--on below line we are creating our linear layout--><LinearLayout    android:id="@+id/idLLContainer"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_centerInParent="true"    android:layout_gravity="center"    android:gravity="center"    android:orientation="vertical"    tools:context=".MainActivity"></LinearLayout> |
Step 3: Working with the MainActivity fileÂ
Navigate to app > java > your app’s package name > MainActivity file and add the code below. Comments are added in the code to get to know in detail.Â
Kotlin
package com.gtappdevelopers.kotlingfgprojectÂ
import android.graphics.Typefaceimport android.os.Bundleimport android.view.Gravityimport android.view.ViewGroupimport android.widget.LinearLayoutimport android.widget.Switchimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivityÂ
class MainActivity : AppCompatActivity() {Â
    // on below line creating a variable.    lateinit var containerLL: LinearLayoutÂ
    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)Â
        // on below line we are initializing our variables.        containerLL = findViewById(R.id.idLLContainer)Â
        // on below line we are creating layout        // params for text view.        // and specifying width as match parent        // and height as wrap content        val txtLayoutParam = LinearLayout.LayoutParams(            ViewGroup.LayoutParams.MATCH_PARENT,            ViewGroup.LayoutParams.WRAP_CONTENT        )Â
        // on below line we are creating        // our dynamic text view        val headingTV = TextView(this)Â
        // on below line we are setting        // for our text view.        headingTV.text = "Dynamic Switch in Android"Â
        // on below line we are updating text size.        headingTV.textSize = 20fÂ
        // on below line we are updating text color and font        headingTV.setTextColor(resources.getColor(R.color.black))        headingTV.typeface = Typeface.DEFAULT_BOLDÂ
        // on below line we are adding padding        headingTV.setPadding(20, 20, 20, 20)Â
        // on below line we are specifying text alignment.        headingTV.textAlignment = TextView.TEXT_ALIGNMENT_CENTERÂ
        // on below line we are adding layout        // param for heading text view.        headingTV.layoutParams = txtLayoutParamÂ
        // on below line we are creating        // a text view for switch status        val statusTV = TextView(this)Â
        // on below line we are setting        // for our text view.        statusTV.text = "Status"Â
        // on below line we are updating text size.        statusTV.textSize = 20fÂ
        // on below line we are updating text color and font        statusTV.setTextColor(resources.getColor(R.color.black))        statusTV.typeface = Typeface.DEFAULT_BOLDÂ
        // on below line we are adding padding        statusTV.setPadding(20, 20, 20, 20)Â
        // on below line we are specifying text alignment.        statusTV.textAlignment = TextView.TEXT_ALIGNMENT_CENTERÂ
        // on below line we are adding layout        // param for heading text view.        statusTV.layoutParams = txtLayoutParamÂ
Â
        // on below line we are creating layout params for switch.        // and specifying width as wrap parent and height as wrap content        val switchLayoutParam = LinearLayout.LayoutParams(            ViewGroup.LayoutParams.WRAP_CONTENT,            ViewGroup.LayoutParams.WRAP_CONTENT        )                 // on below line we are adding gravity        switchLayoutParam.gravity = Gravity.CENTERÂ
        // on below line we are adding margins.        switchLayoutParam.setMargins(10, 10, 10, 10)                 // on below line we are creating a new switch        val switch = Switch(this)                 // on below line we are adding layout params for switch        switch.layoutParams = switchLayoutParamÂ
        // on below line we are        // checking the status of switch        if (switch.isChecked) {            // on below line we are setting text            // if switch is checked.            statusTV.text = "Switch is Checked"        } else {            // on below line we are setting the            // text if switch is un checked            statusTV.text = "Switch is UnChecked"        }Â
        // on below line we are adding check change listener for our switch.        switch.setOnCheckedChangeListener { buttonView, isChecked ->            // on below line we are checking            // if switch is checked or not.            if (isChecked) {                // on below line we are setting text                // if switch is checked.                statusTV.text = "Switch is Checked"            } else {                // on below line we are setting text                // if switch is unchecked.                statusTV.text = "Switch is UnChecked"            }        }Â
        // on below line we are adding our views        // to container linear layout        containerLL.addView(headingTV)        containerLL.addView(statusTV)        containerLL.addView(switch)    }} |
Java
package com.gtappdevelopers.kotlingfgproject;Â
import android.graphics.Typeface;import android.os.Build;import android.os.Bundle;import android.view.Gravity;import android.view.View;import android.view.ViewGroup;import android.widget.CompoundButton;import android.widget.LinearLayout;import android.widget.Switch;import android.widget.TextView;import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity;Â
public class MainActivity extends AppCompatActivity {Â
    // on below line we are creating variables.    private LinearLayout containerLL;Â
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);Â
        // on below line we are initializing our variables.        containerLL = findViewById(R.id.idLLContainer);Â
        // on below line we are creating layout params for text view.        // and specifying width as match parent and height as wrap content        LinearLayout.LayoutParams txtLayoutParam = new LinearLayout.LayoutParams(                ViewGroup.LayoutParams.MATCH_PARENT,                ViewGroup.LayoutParams.WRAP_CONTENT        );        // on below line we are adding gravity        txtLayoutParam.gravity = Gravity.CENTER;Â
        // on below line we are creating our dynamic text view        TextView headingTV = new TextView(this);Â
        // on below line we are setting for our text view.        headingTV.setText("Dynamic Switch in Android");Â
        // on below line we are updating text size.        headingTV.setTextSize(20f);Â
        // on below line we are updating text color and font        headingTV.setTextColor(getResources().getColor(R.color.black));        headingTV.setTypeface(Typeface.DEFAULT_BOLD);Â
        // on below line we are adding padding        headingTV.setPadding(20, 20, 20, 20);Â
        // on below line we are specifying text alignment.        headingTV.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);Â
        // on below line we are adding layout param        // for heading text view.        headingTV.setLayoutParams(txtLayoutParam);Â
Â
        // on below line we are creating our dynamic text view        TextView statusTV = new TextView(this);Â
        // on below line we are setting        // for our text view.        statusTV.setText("Status");Â
        // on below line we are        // updating text size.        statusTV.setTextSize(20f);Â
        // on below line we are updating text color and font        statusTV.setTextColor(getResources().getColor(R.color.black));        statusTV.setTypeface(Typeface.DEFAULT_BOLD);Â
        // on below line we are adding padding        statusTV.setPadding(20, 20, 20, 20);Â
        // on below line we are specifying text alignment.        statusTV.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);Â
        // on below line we are adding layout param        // for heading text view.        statusTV.setLayoutParams(txtLayoutParam);Â
        // on below line we are creating layout params for switch.        // and specifying width as wrap parent and height as wrap content        LinearLayout.LayoutParams switchLayoutParam = new LinearLayout.LayoutParams(                ViewGroup.LayoutParams.WRAP_CONTENT,                ViewGroup.LayoutParams.WRAP_CONTENT        );                   // on below line we are adding gravity        switchLayoutParam.gravity = Gravity.CENTER;Â
        // on below line we are adding margins.        switchLayoutParam.setMargins(10, 10, 10, 10)                 // on below line we are creating a new switch        Switch switchView = new Switch(this);                 // on below line we are adding        // layout params for switch        switchView.setLayoutParams(switchLayoutParam);Â
        // on below line we are checking        // the status of switch        if (switchView.isChecked()) {            // on below line we are setting text            // if switch is checked.            statusTV.setText("Switch is Checked");        } else {            // on below line we are setting the text            // if switch is un checked            statusTV.setText("Switch is UnChecked");        }Â
        // on below line we are adding check change listener for our switch.        switchView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {            @Override            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {                // on below line we are checking                // if switch is checked or not.                if (isChecked) {                    // on below line we are setting text                    // if switch is checked.                    statusTV.setText("Switch is Checked");                } else {                    // on below line we are setting text                    // if switch is unchecked.                    statusTV.setText("Switch is UnChecked");                }            }        });    }} |
Now run your application to see the output of it.Â
Output:
