Create Material Design Custom Switch button in Android

How to change switch button theme in android app using custom style option.

Material style switch button is currently most popular between android developers so in this tutorial we are going to Create Material Design Custom Switch button in Android application with the use of com.android.support:appcompat-v7 library.

Follow the below steps to add appcompat-V7 library in your project:

1. Import the com.android.support:appcompat-v7 library in your project’s build.gradle ( Module:app ) file.

2. Add compile ‘com.android.support:appcompat-v7:25.1.0’ in dependencies scope .

How to Create Material Design Custom Switch button in Android.

Code for MainActivity.java file.

package com.android_examples.materialswitch_android_examplescom;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Code for activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.android_examples.materialswitch_android_examplescom.MainActivity">

    <android.support.v7.widget.SwitchCompat
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:theme="@style/SwitchTheme"/>

</RelativeLayout>

Code for styles.xml file.

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="SwitchTheme" parent="Theme.AppCompat.Light">

        <item name="colorControlActivated">#009688</item>


        <item name="colorSwitchThumbNormal">#1DE9B6</item>


        <item name="android:colorForeground">#B2DFDB</item>
    </style>

</resources>

Screenshot :

Create Material Design Custom Switch

Leave a Reply

Your email address will not be published. Required fields are marked *