customize toggle button on Android

kingston picture kingston · Oct 4, 2012 · Viewed 19.6k times · Source

I customized the Toggle button by using a drawable defined by using a selector. I use this drawable as background for the Toggle button.

<ToggleButton
    android:id="@+id/mailbox:toggle_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_weight="1"
    android:background="@drawable/toggle_background"
    android:gravity="center_horizontal|center_vertical" />

The toggle_background is defined here:

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

The problem is that the image is always stretched. Is there a way to define an image for the two states that is not stretched?

What I need is a background that will be stretched and in the center of the button an icon that must not be stretched.

Is it possible?

Answer

kingston picture kingston · Oct 5, 2012

This is my final solution.

In the layout:

<ToggleButton
    android:id="@+id/mailbox:toggle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"     
    android:background="@drawable/toggle_drawable_layers"/>

in the toggle_drawable_layers.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/toggle_drawable_bkg"></item>
    <item android:left="10dp" android:drawable="@drawable/toggle_drawable_left"
          android:gravity="center_vertical|center_horizontal" />
</layer-list>

in the toggle_drawable_left.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <bitmap android:src="@drawable/bitmap_checked"
          android:gravity="center_vertical|center_horizontal" />
    </item>
    <item android:state_checked="false">
        <bitmap android:src="@drawable/bitmap_unchecked"
          android:gravity="center_vertical|center_horizontal" />
    </item>        
</selector>