Search code examples
javaandroidxmluiswitch

Custom switch in Android with text in track


I have a custom switch. I want the text (on/off) to be in the track and not in the thumb.

I was thinking of setting a selector with text in drawable and setting it as track of the switch. But I cannot set text in a shape. Any ideas how I can do this?

I also want to add some padding to the track, I dont want the thumb to touch the track. This is kind of how I want it to look:

I want the switch to be kind of like this

This is the shape of my track:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:visible="true"
android:useLevel="false">
<corners
    android:radius="20dp" />
<size
    android:width="48dp"
    android:height="21dp" />
<stroke
    android:color="#bfbfbf"
    android:width="6dp"/>


Solution

  • Switch off screenshot

    enter image description here

    Switch on screenshot

    enter image description here

    Switch on image

    enter image description here

    Switch off image

    enter image description here

    Thumb image

    enter image description here

    switch_on_off.xml

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

    xml code

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switch_compat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        app:track="@drawable/switch_on_off"
        android:thumb="@drawable/on_switch_active"/>
    

    Try above code and let me know if you find any error.....