I'm trying to create a custom switch like this:
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With