padmi padmi - 3 months ago 30
Android Question

how to change the background color of the toggle button in android

i tried to change the background color of the toggle button using XML file as white color but the toggle button is totally damaged it look like all the button was covered with white. There is no indication of ON or OFF on the toggle button when i have changed the color of the toggle button to white. Can any one please tell me, Is there is any other way to change the background which will not damage the indication of the toggle button .

<ToggleButton android:id="@+id/togglebutton"
android:layout_width="100px"
android:layout_height="46px"
android:background="#ffffff"
android:layout_above ="@+id/save"
android:textOn="DAY"
android:textOff="NIGHT" />


this is how my XML code look for the toggle button

Answer

Yes there is a way to change the background as you wish but you have to use a selector like this as background:

<selector
xmlns:android="http://schemas.android.com/apk/res/android"
>
<item
    android:state_focused="true"
    android:state_pressed="false"
    android:drawable="@drawable/some_image" />
<item
    android:state_focused="true"
    android:state_pressed="true"
    android:drawable="@drawable/some_other_image" />
<item
    android:state_focused="false"
    android:state_pressed="false"
    android:drawable="@drawable/some_image1" />
<item
    android:state_focused="false"
    android:state_pressed="true"
    android:drawable="@drawable/other_image" />
</selector>

For @Drawable/etc (you can use a color or make a gradient. Check this for more info about gradients