Search code examples
androidxmlandroid-switch

Create custom flat switch android


I want to make one custom switch as shown below.

enter image description here

enter image description here

I have created two drawable resource for that one is switch_bg and another is tracker_bg.

switch_bg.xml

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/thumb_on" android:state_pressed="true" />
    <item android:drawable="@drawable/thumb_off" android:state_enabled="false" />
    <item android:drawable="@drawable/thumb_on" android:state_checked="true" />
    <item android:drawable="@drawable/thumb_off" />
</selector>

tracker_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_tracker" android:state_enabled="false" />
    <item android:drawable="@drawable/ic_tracker" android:state_pressed="true" />
    <item android:drawable="@drawable/ic_tracker" android:state_checked="true" />
    <item android:drawable="@drawable/ic_tracker" />
</selector>

and in main xml I put following code.

<Switch
  android:id="@+id/switch1"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:checked="true"
  android:layout_marginRight="20dp"
  android:thumb="@drawable/switch_bg"
  android:track="@drawable/track_bg"/>

Please guide me What I am doing wrong or What things are missing from my side.


Solution

  • Try this sample it may help you.Click here