Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Width of Android's Switch track?

Tags:

java

android

I'm going crazy with this tiny problem. I have a 'switch' Form widget, but no matter how much I try, I cannot make it narrower. Even if I have one character instead of 'ON' or 'OFF', the size of switch remains the same. The 'thumb' becomes small, but it has to be dragged over the same distance as before. Changing the 'layout_width' to a smaller value simply cuts off the remaining track. 'minWidth' doesnt seem to do anything.

Anybody knows how I can do this? Ideally I want just an empty thumb and I'll colour code both thumb to know which is which.

XML code:

<Switch
     android:id="@+id/switch3"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Switch"
     android:textOff=" "
     android:textOn=" " />

I am gettin this: enter image description here

but I want something like this: enter image description here

like image 796
Snebhu Avatar asked May 16 '13 23:05

Snebhu


3 Answers

Set your desired width of switch in the attribute:

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" />
like image 135
BSKANIA Avatar answered Nov 12 '22 17:11

BSKANIA


Here is my solution. I removed the texts, set the padding of the track and define the switchMinWidth properties. This is my 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" />
like image 24
Pedro Acácio Avatar answered Nov 12 '22 18:11

Pedro Acácio


Who are using androidx.appcompat.widget.SwitchCompat need to use

app:switchMinWidth

Example:

<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"
   />
like image 1
Abu Yousuf Avatar answered Nov 12 '22 16:11

Abu Yousuf