Android switch custom left-right drawables

Mike T picture Mike T · Jun 5, 2015 · Viewed 8.4k times · Source

I'm trying to create a custom switch like this:

custom gender switch

What I feel like I need is something like a left/right drawable each in a green/white state, or alternatively a green outline with a drawable for when the choice should be selected.

What I don't understand in posts like this is how all the sample drawables provided slant to the right, and yet the 'on' button slants to the left.

I'm trying with the following 'thumb' drawable.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"  android:drawable="@drawable/choice_right"/>
    <item                               android:drawable="@drawable/choice_left"/>
</selector>

but it seems to cut the ends off the drawables. If I also set a track to something like this:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" >

        <stroke 
            android:width="1dp" 
            android:color="@color/text_input"/>

        <corners
            android:radius="1dp"
            android:bottomLeftRadius="4.5dp"
            android:bottomRightRadius="4.5dp"
            android:topLeftRadius="4.5dp"
            android:topRightRadius="4.5dp" >
    </corners>
</shape>

then all I get is a thin line. So, I'm not sure what to try next.

Answer

Rajesh Batth picture Rajesh Batth · Jun 13, 2015

This cannot be with styling alone, this needs custom view implementation. Thats lot of code so my suggestion for you would be to use 3rd party libraries like https://github.com/hoang8f/android-segmented-control This library is tried and tested so its safe to use it instead of rewriting it.