Switch in Kotlin Last Updated : 07 Feb, 2025 Comments Improve Suggest changes Like Article Like Report Android Switch is a two-state user interface element that is used to toggle between ON and OFF similar to a button. By tapping the button we can drag it back and forth to make it either ON or OFF. The Switch element is useful when there are only two states required for an activity like to either choose ON or OFF. We can add a Switch to our application layout by using the Switch object. By default, the state for the android Switch is OFF state. We can also change the state of Switch to ON by setting the android:checked = “true” in our XML layout file.In android, we can create Switch control in two ways either by using Switch in XML layout file or creating it in Kotlin file dynamically. In this article, we will discuss how to setup a switch in XML layout.To know about how to setup a switch dynamically in android, refer to Dynamic Switch in Android.Some Important attributes of Switch widgetXML AttributesDescriptionandroid:gravityUsed to specify how to align the text like left, right, center, top, etc.android:checkedUsed to specify the current state of switch control.android:thumbUsed to set drawable to be used as thumb that can be moved back and forth.android:thumbTintUsed to set tint to apply to the thumb.android:textUsed to set the text of the Switch.android:textOnUsed to set the text when toggle button is in ON (Checked) state.android:textOffUsed to set the text when toggle button is in Off (unchecked) state.android:textStyleUsed to set style of the text. For example, bold, italic, bolditalic etc.android:textColorUsed to set color of the text.android:textSizeUsed to set size of the text.android:backgroundUsed to set background color of the toggle button.android:drawableBottomUsed to set drawable to the bottom of the text.android:drawableLeftUsed to set drawable to left of the text.android:drawableRightUsed to set drawable to the right of text.android:paddingUsed to set the padding from left, right, top and bottom.Step by Step ImplementationStep 1: Creating a new project in Android StudioTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Kotlin Programming Language for Android.Step 2: Adding Switch code in activity_main.xml fileIn this file, we will use the LinearLayout and two switches inside it. Set the attributes of each switch like switch id, text etc. activity_main.xml: XML <?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:background="@color/white" android:orientation="vertical"> <androidx.appcompat.widget.SwitchCompat android:id="@+id/switch1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Switch1"/> <androidx.appcompat.widget.SwitchCompat android:id="@+id/switch2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Switch2"/> </LinearLayout> Layout: Step 3: Accessing the Switch widget in MainActivity.kt fileHere, we will access the switches by using their respective id's and set onClickListener and Toast message if a switch is checked(ON) state. First of all, declare a variable to get the switch using it's id. val switch: SwitchCompat = findViewById(R.id.switch)Note: We will be using SwitchCompat in this article. You can also choose to use SwitchMaterial.then, set OnClick listener on the switch and use if condition to check the state of the button. switch?.setOnCheckedChangeListener({ _ , isChecked -> val message = if (isChecked) "Switch:ON" else "Switch:OFF" Toast.makeText(this, message,Toast.LENGTH_SHORT).show()})Repeat the process for another switch in the MainActivity file.MainActivity.kt: Kotlin package org.geeksforgeeks.demo import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SwitchCompat class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val switch1: SwitchCompat = findViewById(R.id.switch1) switch1.setOnCheckedChangeListener { _, isChecked -> val message = if (isChecked) "Switch1:ON" else "Switch1:OFF" Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } val switch2: SwitchCompat = findViewById(R.id.switch2) switch2.setOnCheckedChangeListener { _, isChecked -> val message = if (isChecked) "Switch2:ON" else "Switch2:OFF" Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } } } Output:Here, two switches are shown in the emulator when we run the above code. We can change the state of the switches independently. Comment More infoAdvertise with us Next Article Dynamic Switch in Kotlin P Praveenruhil Follow Improve Article Tags : Kotlin Android Kotlin Android Java-Android Similar Reads Kotlin Android Tutorial Kotlin is a cross-platform programming language that may be used as an alternative to Java for Android App Development. Kotlin is an easy language so that you can create powerful applications immediately. Kotlin is much simpler for beginners to try as compared to Java, and this Kotlin Android Tutori 6 min read TextViewTextView in KotlinAndroid TextView is simply a view that are used to display the text to the user and optionally allow us to modify or edit it. First of all, open Kotlin project in Android Studio. Following steps are used to create Steps to Implement TextViewSteps by Step implementation for creating an application wh 3 min read Dynamic TextView in KotlinAndroid TextView is an user interface that is used to display some text to the user. In this article we will be discussing how to programmatically create a TextView in Kotlin . Step by Step ImplementationStep 1: Create a new projectLetâs start by first creating a project in Android Studio. To do so, 2 min read AutoCompleteTextView in KotlinAndroid AutoCompleteTextView is an advanced EditText which shows a list of suggestions when user starts typing text. When the user starts typing, a drop-down menu appears, showing a list of relevant suggestions based on the user input. The user can then select an item from the list.The AutoCompleteT 3 min read Dynamic AutoCompleteTextView in KotlinAndroid AutoCompleteTextView is an advanced EditText which shows a list of suggestions when user starts typing text. When the user starts typing, a drop-down menu appears, showing a list of relevant suggestions based on the user input. The user can then select an item from the list.The AutoCompleteT 4 min read CheckedTextView in KotlinCheckedTextView is an extension of TextView in Android that includes a checkmark, making it function like a checkbox. It is commonly used in list views where items can be selected or toggled between checked and unchecked states. Users can tap the text to change its checked status, and the checkmark 2 min read Dynamic CheckedTextView in KotlinCheckedTextView is an extension of TextView in Android that includes a checkmark, making it function like a checkbox. It is commonly used in list views where items can be selected or toggled between checked and unchecked states. Users can tap the text to change its checked status, and the checkmark 2 min read ScrollViewHorizontalScrollView in KotlinScrollView in Android allows multiple views that are places within the parent view group to be scrolled. Scrolling in the android application can be done in two ways either Vertically or Horizontally. In this article, we will be discussing how to create a Horizontal ScrollView in Kotlin.Some Importa 2 min read Dynamic ScrollView in KotlinIn Android, ScrollView incorporates multiple views within itself and allows them to be scrolled. In this article we will be discussing how to programmatically create a Scroll view in Kotlin.Step by Step ImplementationStep 1: Create a new projectTo create a new project in Android Studio please refer 2 min read Dynamic Horizontal ScrollView in KotlinAndroid ScrollView allows multiple views that are places within the parent view group to be scrolled. Scrolling in the android application can be done in two ways either Vertically or Horizontally. In this article, we will be discussing how to programmatically create a Horizontal ScrollView in Kotli 2 min read ImageViewDynamic ImageView in KotlinAn ImageView as the name suggests is used to display images in Android Applications. In this article, we will be discussing how to create an ImageView programmatically in Kotlin.Step by Step ImplementationStep 1: Create a new projectTo create a new project in Android Studio please refer to How to Cr 2 min read ListViewAndroid ListView in KotlinListView in Android is a ViewGroup which is used to display a scrollable list of items arranged in multiple rows. It is attached to an adapter which dynamically inserts the items into the list. The main purpose of the adapter is to retrieve data from an array or a database and efficiently push every 3 min read ButtonButton in AndroidIn Android applications, a Button is a user interface that is used to perform some action when clicked or tapped. It is a very common widget in Android and developers often use it. This article demonstrates how to create a button in Android Studio.Class Hierarchy of the Button Class in Kotlinkotlin. 3 min read ImageButton in KotlinAndroid ImageButton is a user interface widget which is used to display a button having image and to perform exactly like button when we click on it but here, we add an image on Image button instead of text. There are different types of buttons available in android like ImageButton, ToggleButton, et 3 min read Dynamic ImageButton in KotlinAn ImageButton in Android is a specialized Button that displays an image instead of text while functioning like a regular button. When clicked, it triggers an action just like a standard button. Android provides various button types, including ImageButton, ToggleButton, and more. To set an image on 2 min read RadioButton in KotlinAndroid Radio Button is bi-state button which can either be checked or unchecked. Also, it's working is same as Checkbox except that radio button can not allow to be unchecked once it was selected. Generally, we use RadioButton controls to allow users to select one option from multiple options. By d 4 min read Dynamic RadioButton in KotlinAn Android RadioButton is a bi-state button that can be either checked or unchecked. It functions similarly to a CheckBox, but with one key difference: once selected, a RadioButton cannot be unchecked by tapping it again. RadioButtons are typically used within a RadioGroup to allow users to select o 2 min read EditTextAndroid EditText in KotlinEditText is a widget in Android, that is used to get input from the user. EditText is commonly used in forms and login or registration screens. EditText extends the TextView class and provides more functionalities including handing text inputs such as cursor control, keyboard display and text valida 3 min read Dynamic EditText in KotlinEditText is a commonly used UI component in Android for getting user input, especially in login and registration screens. While we have already learned how to create an EditText using XML layouts, this article will focus on how to create an EditText programmatically in Kotlin.Step by Step Implementa 2 min read LayoutsAndroid UI LayoutsLayouts in Android define the user interface and hold UI controls or widgets that appear on the screen of an application. Every Android application consists of View and ViewGroup elements. Since an application contains multiple activitiesâeach representing a separate screenâevery activity has multip 5 min read Android TableLayout in KotlinTableLayout in Android is a ViewGroup subclass that is designed to align child views in rows and columns like a grid structure. It automatically arranges all the child elements into rows and columns without displaying any border lines between cells. The Table Layout's functionality is almost similar 3 min read FrameLayout in AndroidAndroid Framelayout is a ViewGroup subclass that is used to specify the position of multiple views placed on top of each other to represent a single view screen. Generally, we can say FrameLayout simply blocks a particular area on the screen to display a single view. Here, all the child views or ele 3 min read Android RelativeLayout in KotlinRelativeLayout in Android is a ViewGroup subclass, that allows users to position child views relative to each other (e.g., view A to the right of view B) or relative to the parent (e.g., aligned to the top of the parent). Instead of using LinearLayout, we have to use RelativeLayout to design the use 4 min read Android LinearLayout in KotlinLinearLayout in Android is a ViewGroup subclass, used to arrange child view elements one by one in a singular direction either horizontally or vertically based on the orientation attribute. We can specify the linear layout orientation using the android:orientation attribute. All the child elements a 2 min read BarSeekBar in KotlinSeekBar in Android is a modified version of progressBar that has a draggable thumb in which a user can drag the thumb back and forth to set the current progress value. We can use SeekBar in our Android Devices like Brightness control, volume control etc. It is one of the important user interface ele 3 min read Dynamic SeekBar in KotlinSeekBar in Android is a modified version of progressBar that has a draggable thumb in which a user can drag the thumb back and forth to set the current progress value. We can use SeekBar in our Android Devices like Brightness control, volume control etc. It is one of the important user interface ele 2 min read Discrete SeekBar in KotlinIn Android Discrete SeekBar is just an advancement of progressBar just like the SeekBar, the only difference in SeekBar and discrete SeekBar being that in discrete SeekBar, we can only set the value only to discrete values like 1, 2, 3, and so on. In this article, we will be discussing how to create 2 min read RatingBar in KotlinAndroid RatingBar is a user interface widget which is used to get the rating from the customers or users. It is an extension of SeekBar and ProgressBar that shows star ratings and it allow users to give the rating by clicking on the stars. In RatingBar, we can set the step size using android:stepSiz 3 min read Dynamic RatingBar in KotlinAndroid RatingBar is a user interface widget which is used to get the rating from the customers or users. It is an extension of SeekBar and Progress Bar that shows star ratings and it allow users to give the rating by clicking on the stars.In RatingBar, we can set the step size using android:stepSiz 3 min read ProgressBar in KotlinAndroid ProgressBar is a user interface control that indicates the progress of an operation. For example, downloading a file, uploading a file on the internet we can see the progress bar to estimate the time remaining in operation. There are two modes of ProgressBarDeterminate ProgressBarIndetermina 3 min read Dynamic ProgressBar in KotlinAndroid ProgressBar is user interface control that is used to show some kind of progress. For instance, loading of some page, downloading of some file or waiting for some event to complete. In this article we will be discussing how to programmatically create a progress bar in Kotlin.Step by Step Imp 2 min read SwitcherSwitch in KotlinAndroid Switch is a two-state user interface element that is used to toggle between ON and OFF similar to a button. By tapping the button we can drag it back and forth to make it either ON or OFF. The Switch element is useful when there are only two states required for an activity like to either cho 3 min read Dynamic Switch in KotlinAndroid Switch is also a two-state user interface element that is used to toggle between ON and OFF as a button. By touching the button we can drag it back and forth to make it either ON or OFF.The Switch element is useful when only two states require for activity either choose ON or OFF. We can add 2 min read TextSwitcher in KotlinAndroid TextSwitcher is a user interface widget that contains a number of textView and displays one at a time. Textswitcher is a subclass of View Switcher which is used to animate one text and display the next one. Generally, we use TextSwitcher in two ways manually in XML layout and programmaticall 3 min read Dynamic TextSwitcher in KotlinAndroid TextSwitcher is a user interface widget that contains number of textView and displays one at a time. Textswitcher is subclass of View Switcher which is used to animates one text and displays next one. Here, we create TextSwitcher programmatically in Kotlin file. Steps of Implementing Dynamic 2 min read ImageSwitcher in KotlinAndroid ImageSwitcher is a user interface widget that provides a smooth transition animation effect to the images while switching between them to display in the view. ImageSwitcher is subclass of View Switcher which is used to animates one image and displays next one. Generally, we use ImageSwitcher 3 min read Dynamic ImageSwitcher in KotlinAndroid ImageSwitcher is a user interface widget that provides a smooth transition animation effect to the images while switching between them to display in the view. ImageSwitcher is subclass of View Switcher which is used to animates one image and displays next one. Here, we create ImageSwitcher p 3 min read Like