Jignesh Ansodariya Jignesh Ansodariya - 1 year ago 121
Android Question

click effect on button in Android

in android while I set background image to Button I can not see any effect on button.
I need some effect on button so user can recognize that button is clicked.
Button should be dark while a few second when it clicked , so what should I do for this ?

Answer Source

This can be achieved by creating a drawable xml file containing a list of states for the button. So for example if you create a new xml file called "button.xml" with the following code:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/YOURIMAGE" />
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/gradient" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/gradient" />
    <item android:drawable="@drawable/YOURIMAGE" />

To keep the background image with a darkened appearance on press, create a second xml file and call it gradient.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
        <bitmap android:src="@drawable/YOURIMAGE"/>
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <gradient android:angle="90" android:startColor="#880f0f10" android:centerColor="#880d0d0f" android:endColor="#885d5d5e"/>

In the xml of your button set the background to be the button xml e.g.


Hope this helps!

Edit: Changed the above code to show an image (YOURIMAGE) in the button as opposed to a block colour.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download