Custom switch in Android with text in track

僤鯓⒐⒋嵵緔 提交于 2019-12-12 11:31:20

问题


I have a custom switch. I want the text (on/off) to be in the track and not in the thumb.

I was thinking of setting a selector with text in drawable and setting it as track of the switch. But I cannot set text in a shape. Any ideas how I can do this?

I also want to add some padding to the track, I dont want the thumb to touch the track. This is kind of how I want it to look:

This is the shape of my track:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:visible="true"
android:useLevel="false">
<corners
    android:radius="20dp" />
<size
    android:width="48dp"
    android:height="21dp" />
<stroke
    android:color="#bfbfbf"
    android:width="6dp"/>


回答1:


Switch off screenshot

Switch on screenshot

Switch on image

Switch off image

Thumb image

switch_on_off.xml

    <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/on_switch"/>
    <item android:state_checked="false" android:drawable="@drawable/off_switch"/>
    <item android:drawable="@drawable/off_switch"/>
</selector>

xml code

<android.support.v7.widget.SwitchCompat
    android:id="@+id/switch_compat"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    app:track="@drawable/switch_on_off"
    android:thumb="@drawable/on_switch_active"/>

Try above code and let me know if you find any error.....



来源:https://stackoverflow.com/questions/43914326/custom-switch-in-android-with-text-in-track

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!