Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android switch custom left-right drawables

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.

like image 512
Mike T Avatar asked Jun 05 '15 21:06

Mike T


2 Answers

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.

like image 123
Rajesh Batth Avatar answered Sep 29 '22 22:09

Rajesh Batth


I have created an example app that you can find here that should solve your problem. You can have a look at this library that has a proper implementation of the segment control.

Basically I created a custom control that extends LinearLayout with a default weightSum of 2. Two Buttons are added with a weight of 1 and some logic is applied to toggle between them. On toggle an custom event is fired that is built on this interface.

public interface SwitchToggleListener {
    void onSwitchToggle(SwitchToggleState switchToggleState);
}

I used drawable resources to style the buttons.

The final result looked like this

enter image description here

like image 30
the-ginger-geek Avatar answered Sep 30 '22 00:09

the-ginger-geek