0

I am trying to customize SwitchCompat with png images. I want my switch to look like this:

a switch with a racetrack like shape.

How can I accomplish this?

I have tried putting a png for "track" and "thumb" of SwitchCompat each. So far I am only successful in putting the "track" in the desired shape. With "thumb" I have had no such luck. I have tried the solutions provided in this answer:

How to change the size of a Switch Widget

But it only discusses making drawables using xml resources.

I have tried using scaleX and scaleY but the thumb does not give the same shape as in png.

Here is what I have tried:

<androidx.appcompat.widget.SwitchCompat
        android:id="@+id/on_blue_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:rotation="90"
        android:thumb="@drawable/ic_thumb"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:background="@drawable/ic_track"
        android:scaleY="1"
        android:scaleX="1"
        />

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false">
        <bitmap android:src="@drawable/ic_thumb"
            android:gravity="center"
            android:dither="false"/>

    </item>
</selector>

I want my switch to look like this:

https://i.stack.imgur.com/5kohI.png

But it looks like this:

https://i.stack.imgur.com/cZGTv.jpg

Muhammad Ali
  • 683
  • 4
  • 9

1 Answers1

-1

Please add some changes in your xml file like below:

<androidx.appcompat.widget.SwitchCompat
        android:id="@+id/on_blue_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:rotation="90"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:background="@drawable/ic_track"
        android:thumb="@null"
        android:track="@null"/>

thumb and track set as null and set only background to switch i.e ic_track

ic_track.xml

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

switch_yes is that image which is set when check state of switch is true.

switch_no is that image which is set when check state of switch is false.

I hope its work for you.

Android Geek
  • 8,956
  • 2
  • 21
  • 35