Jim Vitek
Jim Vitek

Reputation: 4214

Android Switch widget textOn and textOff not working in Lollipop

The behavior of the switch widget changed in 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"
        />

Rendered switch when targetSdkVersion=19:

enter image description here

Rendered switch when targetSdkVersion=21:

enter image description here

Note that preview rendering in Android Studio still produces a switch with text, but the switch loses it's text when an apk built with targetSdkVersion=21 is run on a device with Lollipop (Nexus 5). Running an apk built with targetSdkVersion=19 on the same Lollipop device renders the switch properly with text as expected.

Why? Any suggested workarounds?

Upvotes: 56

Views: 32379

Answers (1)

alanv
alanv

Reputation: 24124

Text is not shown by default under Material theme since the switch widget assets don't work well with text. Any text that you do set will be used to describe the content to accessibility services.

You can change this using the android:showText property or Switch.setShowText(boolean) method.

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

If you are using AppCompat switches, use app:showText instead.

Upvotes: 142

Related Questions