Search code examples
androidandroid-layoutandroid-buttonmaterial-components-androidandroid-switch

Customise Android SwitchCompat


In my Android app, I have a list with a SwitchCompat to filter the list data. The default theme can't serve my purpose what I need is a iOS like switch. I have no idea how can I customize it to look exactly like the iOS switch. Thanks for reading.

            <androidx.appcompat.widget.SwitchCompat
                android:id="@+id/switch_1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:background="@xml/custom_switch_background_main"
                android:theme="@style/AppTheme.SwitchOverlay"/>

Current theme Dream theme

This is what I have archived so far

enter image description here

custom_switch_background_main.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="@xml/custom_switch_background"  />
    <item android:state_checked="true" android:drawable="@xml/custom_switch_background"  />
</selector>

custom_switch_background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="50dp" />
    <solid android:color="@color/transparent" />
    <stroke
        android:width="1dp"
        android:color="@color/hello" />
</shape>

This is what I want

enter image description here


Solution

  • I achieved the design by using a custom vector (and the text inside was a mask) which was replacement for the switch’s state indicator. then I changed the switch compat background vector with a custom border design as well to achieve the border. I’ll update this answer again soon.