Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 391
Jim Vitek Avatar asked Dec 03 '14 15:12

Jim Vitek


1 Answers

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.

like image 190
alanv Avatar answered Oct 17 '22 19:10

alanv