Pages

Saturday 9 March 2013

Android - Button's different state effects using single image



Create an XML file for button selector :
buton_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/my_button" android:state_pressed="false"/>

    <item android:drawable="@drawable/button_pressed" android:state_pressed="true"/>

</selector>
Here my_button is an image in drawable folder and button_pressed is an XML file in drawable.
button_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <bitmap android:src="@drawable/my_button" />
    </item>
    <item>
        <color android:color="#60000000" />
        <!--
        <shape>
            <gradient
                android:endColor="#ff0000"
                android:startColor="#00ff00" />            
            <corners android:radius="3dp" />
        </shape>
        -->
    </item>
</layer-list>
Now set button's background as buton_selector.
<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"        
        android:background="@drawable/button_selector"        
        android:text="my botton" />

Note : We can also use shape,gradient,stroke (See commented part of button_pressed.xml) for rounded button backgrounds!

No comments :

Post a Comment