如何更改Android开关轨道的宽度?

31
我被这个微小的问题搞疯了。我有一个“开关”表单小部件,但无论我尝试多少次,我都无法使它变窄。即使我只有一个字符而不是“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=" " />
我得到了这个:在此输入图片描述,但我想要这样的:在此输入图片描述

展示你的 XML 代码。 - chopchop
android:layout_width="<任何小于wrap_content的较小值>" - Justin Jasmann
裁剪掉了?那很奇怪。缩小父容器并查看发生了什么,或在父容器内插入填充。如果您发布您所担心的XML,那将会很有帮助。 - Justin Jasmann
@NeilDA如果下面的答案解决了您的问题,请将其标记为正确答案。它已经解决了我的问题。请求管理员进行标记。 - Zen
@alexsummers,我从未测试下面的答案,因为我早就完成了应用程序。但是,我也使用了自定义的拇指和轨道,而没有对宽度等进行任何修改,以实现所需的结果。无论如何,我会将其标记为正确的。 - Snebhu
显示剩余5条评论
4个回答

72

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

android:switchMinWidth
例如:

for example:

<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" />

2
这会削减开关的左侧部分。有什么建议可以实现对称开关吗? - user2511882
是的,如果您使用默认开关,则仅修剪右侧部分。我曾经在开关的自定义可绘制对象中使用过这个解决方案。 - BSKANIA
7
花了近两周时间研究解决方案,一直尝试使用“setminWidth”,你是救命恩人!附注:我使用的是switchMinWidth="0dp"。这样开关就可以根据可绘制对象进行缩放。 - Zen
2
无法将宽度设置为小于2倍拇指大小。 - Zhming

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" />

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"
   />

-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" />

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