Mulgard
Mulgard

Reputation: 10569

Styling a switch how to set correct images

I have two graphics:

enter image description here

and:

enter image description here

the first graphic should be kind of a background of the switch but when i set it:

android:background="@drawable/custom_background"

The image is not set. there is still no background at all. I could set the second graphic successfully using:

android:thumb="@drawable/custom_switch_thumb"

How can i set the background of the switch?

Upvotes: 0

Views: 34

Answers (1)

peshkira
peshkira

Reputation: 6229

Use android:track="@drawable/custom_background"

If you want to add color to your custom switch, you can also use selectors for the track and thumb and then use your coloured images in the selectors. This will allow you do provide some visual feedback of the current switch state to the user

Update

In your drawable folder create a file called switch_bg.xml with the following contents. switch_bg_on and switch_bg_off are the images used for the track. Make use of the colors you want for the on and off states.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_checked="true"  android:drawable="@drawable/switch_bg_on" />
  <item                               android:drawable="@drawable/switch_bg_off" />
</selector>

Then create a file switch_thumb.xml in the drawable folder. switch_thumb_on and switch_thumb_off are images again.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_checked="true"  android:drawable="@drawable/switch_thumb_on" />
  <item                               android:drawable="@drawable/switch_thumb_off" />
</selector>

Then in your switch view use something like the following:

<Switch 
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:track="@drawable/switch_bg"
   android:thumb="@drawable/switch_thumb" />

Upvotes: 1

Related Questions