Open In App

How to Create Custom Switch Button in Android?

Last Updated : 14 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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: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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads