androidandroid-buttonandroid-stylesandroid-switch

How to custom switch button?


I am looking to Custom The Switch Button to becoming as following :

enter image description here

How to achieve this ?


Solution

  • However, I might not be taking the best approach, but this is how I have created some Switch like UIs in few of my apps. Here is the code -

    <RadioGroup
            android:checkedButton="@+id/offer"
            android:id="@+id/toggle"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginBottom="@dimen/margin_medium"
            android:layout_marginLeft="50dp"
            android:layout_marginRight="50dp"
            android:layout_marginTop="@dimen/margin_medium"
            android:background="@drawable/pink_out_line"
            android:orientation="horizontal">
    
            <RadioButton
                android:layout_marginTop="1dp"
                android:layout_marginBottom="1dp"
                android:layout_marginLeft="1dp"
                android:id="@+id/search"
                android:background="@drawable/toggle_widget_background"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:button="@null"
                android:gravity="center"
                android:text="Search"
                android:textColor="@color/white" />
    
            <RadioButton
                android:layout_marginRight="1dp"
                android:layout_marginTop="1dp"
                android:layout_marginBottom="1dp"
                android:id="@+id/offer"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/toggle_widget_background"
                android:button="@null"
                android:gravity="center"
                android:text="Offers"
                android:textColor="@color/white" />
        </RadioGroup>
    

    pink_out_line.xml

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <corners android:radius="2dp" />
        <solid android:color="#80000000" />
        <stroke
            android:width="1dp"
            android:color="@color/pink" />
    </shape>
    

    toggle_widget_background.xml

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@color/pink" android:state_checked="true" />
        <item android:drawable="@color/dark_pink" android:state_pressed="true" />
        <item android:drawable="@color/transparent" />
    </selector>
    

    And here is the output -enter image description here