如何在安卓系统中自定义开关

12

enter image description here

我需要在我的应用程序中实现这种类型的开关


欢迎来到Stack Overflow,不过您的问题显示出缺乏研究,而且请注意,StackOverflow既不是论坛、教程网站,也不是网络搜索替代品。我们可以帮助解决某些问题,但首先需要您自己付出一些努力,包括基本的(再)搜索。请阅读如何提出完美问题。FYI - AskNilesh
可能是如何自定义开关按钮?的重复问题。 - V-rund Puro-hit
看看这个库,它可以做你想要的 https://github.com/Angads25/android-toggle - Mr. Patel
1个回答

33
您可以使用以下提供的代码。您可能需要在thumb_selector文件中调整高度和宽度。
<android.support.v7.widget.SwitchCompat
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:thumb="@drawable/thumb_selector"
    app:track="@drawable/track_selector" />

track_selector.xml

    <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape android:dither="true" android:shape="rectangle" android:useLevel="false" android:visible="true">
            <solid android:color="@color/light_pink" />
            <corners android:radius="50dp" />
            <size android:width="2dp" android:height="24dp" />
        </shape>
    </item>
    <item android:state_checked="false">
        <shape android:dither="true" android:shape="rectangle" android:useLevel="false" android:visible="true">

            <corners android:radius="50dp" />
            <size android:width="2dp" android:height="24dp" />
            <stroke
                android:width="2dp"
                android:color="@color/white" />
        </shape>
    </item>
</selector>

thumb_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false">
        <shape android:dither="true" android:shape="rectangle" android:useLevel="false" android:visible="true">
            <solid android:color="#ffffff" />
            <corners android:radius="100dp" />
            <size android:width="18dp" android:height="18dp" />
            <stroke android:width="4dp" android:color="#0000ffff" />
        </shape>
    </item>
</selector>

3
这里不应该使用矩形。请使用android:shape="oval"。 - android6p

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接