28

这个小问题我快疯了。我有一个“切换”表单小部件,但无论我如何尝试,我都无法使其更窄。即使我有一个字符而不是“ON”或“OFF”,开关的大小也保持不变。“拇指”变小了,但它必须像以前一样拖过相同的距离。将“layout_width”更改为较小的值只会切断剩余的轨道。'minWidth' 似乎没有做任何事情。

有人知道我该怎么做吗?理想情况下,我只想要一个空拇指,我会对两个拇指进行颜色编码以知道哪个是哪个。

XML 代码:

<Switch
     android:id="@+id/switch3"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Switch"
     android:textOff=" "
     android:textOn=" " />

我得到这个:在此处输入图像描述

但我想要这样的东西: 在此处输入图像描述

4

4 回答 4

69

在属性中设置所需的开关宽度:

android:switchMinWidth

例如:

<Switch
    android:id="@+id/switchVisitAgain"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:layout_margin="1dp"
    android:checked="false"
    android:gravity="center_vertical"
    android:switchMinWidth="56dp"
    android:textOff=""
    android:textOn=""
    android:thumb="@drawable/round_button"
    android:track="@drawable/button_black" />
于 2013-06-24T10:57:16.193 回答
3

这是我的解决方案。我删除了文本,设置了轨道的填充并定义了switchMinWidth属性。这是我的xml:

<Switch
    android:id="@+id/theSwitchId"
    android:textOn=""
    android:textOff=""
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:thumbTextPadding="5dp"
    android:switchMinWidth="40dp"
    android:layout_gravity="right|center_vertical" />
于 2015-08-16T16:11:30.640 回答
1

谁在使用androidx.appcompat.widget.SwitchCompat需要使用

app:switchMinWidth

例子:

<androidx.appcompat.widget.SwitchCompat
    android:id="@+id/switch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:switchMinWidth="50dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    app:track="@drawable/custom_track"
    android:thumb="@drawable/custom_thumb"
   />
于 2020-12-16T08:07:28.570 回答
-2

您应该使用android:track而不是android:thumb.

我所有的代码:

<Switch
    android:id="@+id/switch_security_tog"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="16dp"
    android:background="@color/transparent"
    android:button="@null"
    android:textOff=""
    android:textOn=""
    android:thumb="@null"
    android:switchMinWidth="56dp"
    android:track="@drawable/thumb" />
于 2017-09-07T02:54:26.030 回答