9

I am trying to make a listview with an on/off switch. I found this simple code but the problem is it is not working for me.

<Switch
    android:id="@+id/itemListSwitch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOn="Vibrate on"
    android:textOff="Vibrate off"/>

Yes, it displays a switch but the text (Vibrate on/off) is not. Only a circle that can be switched is displayed. I want to post a screenshot but i am not allowed to because i lack reputation. Can anyone tell me why because i tried to find answers but a simple code like the one above is working for them. If it helps, my Android phone version is 5.0.2. Thanks in advance!

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Chester Lim
  • 459
  • 7
  • 19

1 Answers1

17

First of all you should use SwitchCompat in order to make it compatible with all android versions and have the nice look of material design of the switch.

Back to your problem, you are missing an attribute for showing the text -app:showText -, here is an example:

<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  ...>
    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switch_compat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="50dp"
        android:layout_marginStart="50dp"
        android:layout_marginTop="25dp"
        android:checked="false"
        android:textOff="OFF"
        android:textOn="ON"
        app:showText="true"/>
</RelativeLayout>
George
  • 271
  • 3
  • 12
  • 3
    Thank you George! This worked! But not what i was expecting. The text is written inside the circle (slider) and not behind it which looks awkward. And is there any way i can change the size and style of the switch? Or am i obliged to use android:background like what others are doing? Thank you very much for the answer and i am hoping for your response on this one! – Chester Lim Jun 09 '15 at 08:16
  • Yes you can, but you will need to extend SwitchCompat class. Take a look here https://gist.github.com/T-Spoon/fe9f0ee8cbb79049b1ec – George Jun 09 '15 at 12:01
  • Hi George. I tried using the SwitchCompatFix by making the said class in a different java file and used it instead of using the SwitchCompat class for my button. I programmatically created one and add it to the layout view but the result is still the same with SwitchCompat, the text is still being showed on top of the slider.Thank you and hoping for your response! :) – Chester Lim Jun 10 '15 at 10:26