Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android switch - change background of switch at on / off

Tags:

android

xml

does someone know how I can implement a switch like this in my application? enter image description here

or how I change the backgroundcolor of standard switch on switching on/off?

like image 818
prototype0815 Avatar asked Mar 11 '15 07:03

prototype0815


1 Answers

Here is sample XML for you to start off with:

<Switch
    android:layout_width="75dp"
    android:layout_height="25dp"
    android:id="@+id/switch1"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:track="@drawable/switch_track_selector"
    android:switchMinWidth="75dp"
    android:thumb="@drawable/switch_thumb_selector" />

switch_track_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/switch_track_on"
        android:state_checked="true"/>

    <item
        android:drawable="@drawable/switch_track_off"
        android:state_checked="false"/>

</selector>

switch_track_on.xml

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners
        android:radius="15dp" />
    <size
        android:width="75dp"
        android:height="25dp" />
    <solid
        android:color="#3E98F3" />
    <stroke
        android:width="1dp"
        android:color="#000000" />
</shape>

switch_track_off.xml

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners
        android:radius="15dp" />
    <size
        android:width="75dp"
        android:height="25dp" />
    <solid
        android:color="#FFFFFF" />
    <stroke
        android:width="1dp"
        android:color="#000000" />
</shape>

switch_thumb_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:drawable="@drawable/switch_thumb"
        android:state_checked="true"/>

    <item 
        android:drawable="@drawable/switch_thumb"
        android:state_checked="false"/>

</selector>

switch_thumb.xml

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <size
        android:width="25dp"
        android:height="25dp" />

    <solid
        android:color="#CCCCCC" />

    <stroke
        android:width="1dp"
        android:color="#000000" />

</shape>
like image 128
dev.bmax Avatar answered Oct 21 '22 03:10

dev.bmax