How to Create Custom Switch Button in Android?
Last Updated :
14 Feb, 2022
In Android, a Switch is a type of button that lets the user toggle between two actions or instances. In general, a Switch is used for selecting one between two options that can be invoking any actions or functions. A sample Switch is shown in the below image. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
In this article, we will show you how you could customize a Switch to appear better in Android. Follow the below steps once the IDE is ready.
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. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Create a custom_switch.xml file and write the following code
Navigate to res > drawable. Right-click on the drawable folder, go to new, and click on Drawable Resource File. Now set the name as custom_switch, root element as the selector, and click OK. Now add the below code to your file. The below code represents two states on the Switch, when true and when false. When true, the color is green, and when false the color is red.
XML
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<shape android:dither="true" android:shape="rectangle" android:useLevel="false" android:visible="true">
<corners android:radius="15dp" />
<gradient android:angle="270" android:endColor="#6600FF00" android:startColor="#66AAFF00" />
<size android:width="37dp" android:height="37dp" />
<stroke android:width="4dp" android:color="#0000ffff" />
</shape>
</item>
<item android:state_checked="false">
<shape android:dither="true" android:shape="rectangle" android:useLevel="false" android:visible="true">
<corners android:radius="15dp" />
<gradient android:angle="270" android:endColor="#ff0000" android:startColor="#ff0000" />
<size android:width="37dp" android:height="37dp" />
<stroke android:width="4dp" android:color="#0000ffff" />
</shape>
</item>
</selector>
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a Switch as shown below. Set the thumb attribute as the custom switch created in the above code.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Switch
android:id="@+id/switch_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="ON"
android:layout_centerInParent="true"
android:textOff="OFF"
android:thumb="@drawable/custom_switch"
tools:ignore="UseSwitchCompatOrMaterialXml" />
</RelativeLayout>
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
package org.geeksforgeeks.switchwidget
import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.Switch
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
@SuppressLint("UseSwitchCompatOrMaterialCode")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mSwitch = findViewById<Switch>(R.id.switch_1)
// Display Toasts in each of true and false case
mSwitch.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
Toast.makeText(applicationContext, "Switch On", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(applicationContext, "Switch Off", Toast.LENGTH_SHORT).show()
}
}
}
}
Output:
You can see that when the Switch is false, the color of the thumb is Red. When the Switch is clicked, the Switch turns true and the thumb color changes to Green.
Similar Reads
How to Create a Custom Stepper Form in Android?
In this article, we are going to implement the multi-step form in modern Android apps. The basic working of that is when User Clicks on the Next Button then a new form comes with different input fields. Also, we have added a step indicator feature to track the user's progress through the steps. Also
5 min read
How to Change Button Font in Android?
A Button in Android is a UI element provided to a user to click to perform a certain action. A text can be set inside the button to name it. However, this text can be seen in a particular font only which is set by default. So in this article, we will show you how you could change the Button text fon
2 min read
How to Create Buttons Inside a Widget in Android?
PrerequisitesHow to Create a Basic Widget of an Android App?How to Create a Dynamic Widget of an Android App?A Widget is a mini version of an Application, that provides a ground for the user to navigate through it or use its features from the Home Screen or Lock Screen. Widgets contain elements acco
4 min read
How to Save Switch Button State in Android?
In Android, a Switch is a type of button that lets the user toggle between two actions or instances. In general, a Switch is used for selecting one between two options that can be invoking any actions or functions. In this article, we are going to see how we can save the state of the Switch Button i
3 min read
How to Create a Custom Intro Slider of an Android App?
Intro Slider in many apps is mostly used to educate the users about the app, the features of the app, and the services that our app will provide to us. In this article, we will take a look at the implementation of Custom Intro Slider in our app. What we are going to build in this Article? We will be
8 min read
How to Create Custom Loading Button By Extending ViewClass in Android?
In this article, we are going to create a custom loading button by extending the View class and animate properties of the custom button once itâs clicked. We had come across many times while downloading any file and keeping our eyes on the downloading progress. Here we will only create that custom b
5 min read
How to Create Dialog with Custom Layout in Android?
In Android, A dialog is a small window that prompts the user to make a decision, provide some additional information, and inform the user about some particular task. The following are the main purposes or goals of a dialog To warn the user about any activity.To inform the user about any activity.To
3 min read
How to Create a Custom AlertDialog in Android?
In some cases for the AlertDialog, there is a need to get input from the user or customize it according to our requirements. That's where custom AlertDialogs comes in handy. In this article we are going to discuss on how to customize the AlertDialogs and take user input.Example: Steps to Implement o
2 min read
How to create customized Buttons in Android with different shapes and colors
A Button is a user interface that are used to perform some action when clicked or tapped. Default Shape of Button In this article, we will try to change the shape and color of Button to various designs, like: Oval Button Rectangular Button Cylindrical Button Approach: Below are the various steps to
4 min read
How to Create Blink Effect on TextView in Android?
In this article, we are going to implement a very important feature related to TextView. Here we are adding the blink text feature on a TextView. This feature can be used to show important announcements or notifications in an App. Even we can add this feature to show important links for the user. So
2 min read