55

在 Lollipop (5.0) 中切换小部件的行为发生了变化。

    <Switch
        android:id="@+id/switcher"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginBottom="16dp"
        android:layout_marginRight="8dp"
        android:layout_marginEnd="8dp"
        android:layout_toEndOf="@id/another_view"
        android:layout_toRightOf="@id/another_view"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:textOff="@string/disabled"
        android:textOn="@string/enabled"
        android:fontFamily="sans-serif-condensed"
        />

targetSdkVersion=19 时渲染的开关:

在此处输入图像描述

targetSdkVersion=21 时渲染的开关:

在此处输入图像描述

请注意,Android Studio 中的预览渲染仍会产生一个带有文本的开关,但当在具有 Lollipop (Nexus 5) 的设备上运行使用 targetSdkVersion=21 构建的 apk 时,该开关会丢失其文本。在同一个 Lollipop 设备上运行使用 targetSdkVersion=19 构建的 apk 会按预期正确地使用文本呈现开关。

为什么?任何建议的解决方法?

4

1 回答 1

139

默认情况下,Material 主题下不显示文本,因为切换小部件资产不适用于文本。您设置的任何文本都将用于向无障碍服务描述内容。

您可以使用android:showText属性或Switch.setShowText(boolean)方法来更改它。

<Switch
    ...
    android:showText="true" />

如果您使用的是 AppCompat 开关,请app:showText改用。

于 2014-12-03T17:44:23.447 回答