如何在 android 中添加圆角矩形 toggle_switch?

how to add a rounded rectangular toggle_switch in android?

我需要在 android 中制作一个圆角矩形 toggle_switch,如下所示:

任何人都可以指导我执行此操作的完整步骤。

给你:

http://developer.android.com/guide/topics/ui/controls/togglebutton.html

显示的确切图像由所谓的 'selector' 或 'state list' 决定,它们是 XML 的一部分,将按钮状态映射到图像。

http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

您需要:

  1. 为按钮的所有可能状态(切换、按下等)准备图像并将它们放在可绘制文件夹中
  2. 编写一个状态列表(选择器),将图像与按钮状态绑定
  3. 将此状态列表连接到按钮 android:background 属性

我按如下方式解决了我的问题:

在我的 xml 布局文件中添加了一个切换按钮:

<ToggleButton
                android:id="@+id/ToggleButton1"
                android:layout_width="120dp"
                android:layout_height="25dp"
                android:layout_marginRight="30dp"
                android:layout_weight="2"
                android:background="@drawable/toogle_switch"
                android:text="ToggleButton"
                android:textOff=""
                android:textOn="" />

然后在 'drawable' 文件夹中定义了一个自定义切换按钮背景 "toogle_switch",如下所示:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/switchon" android:state_checked="true"></item>
    <item android:drawable="@drawable/switchoff" android:state_checked="false"></item>

</selector>

switchon 和 switchoff 是我在问题中显示的 2 个图像。

希望对大家有所帮助! :)