Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change height and width of Switch in Android

  1. I woudld like to fit the switch in 120dp width and 30dp height.
  2. Also I want to no text in the thumb but would like to have the thumb cover half of the total width so i want it to be 60dp.
  3. Also, I want the height of the thumb to be little less than the height of the switch of the background could be seen from 3 sides.

I have no idea how to do #3 and for #1 and #2, I tried the following xml, but it is not working:

 <Switch
         android:id="@+id/plug_switch"
         android:layout_width="120dip"
         android:layout_height="10dp"
         android:maxHeight="10dp"
         android:layout_below="@id/plug_graph_layout"
         android:layout_centerHorizontal="true"
         android:minWidth="100dp"
         android:thumb="@drawable/plugs_button"
         android:track="@drawable/btntoggle_selector"
         android:textOn=""
        android:textOff=""
         android:width="120dip" />

could someone please help me with #1, #2 and #3.

Thanks

like image 737
Sunny Avatar asked Dec 24 '13 14:12

Sunny


1 Answers

final int switchWidth = Math.max(
    mSwitchMinWidth,
    2 * mThumbWidth + paddingLeft + paddingRight);

final int switchHeight = Math.max(trackHeight, thumbHeight);
mSwitchWidth = switchWidth;

The code above is method onMeasure() in class Switch, set android:switchMinWidth can not change the width properly, the only easy way is that change field mSwitchWidth by reflection dynamically:

try {
    Class clazz = Class.forName(Switch.class.getName());
    final Field switchWidth = clazz.getDeclaredField("mSwitchWidth");

    if (switchWidth != null) {
        switchWidth.setAccessible(true);        
        int width = widthWhateverYouWant;
        switchWidth.set(switchClassInstance, width);
        setMeasuredDimension(width, getMeasuredHeight());
        return;
    }
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (NoSuchFieldException e) {
    e.printStackTrace();
}

Do not forget setMeasuredDimension(width, getMeasuredHeight());, because measuredWidth of Switch is not base on field mSwitchWidth.

I guess it's not difficult to change height since you know how to change width :)

like image 177
y4n9b0 Avatar answered Sep 29 '22 08:09

y4n9b0