How to make button with custom background image show click animation in Android

You can create a simple transparent black image, and create a level-list drawable by which u can place the transparent image over the actual image. This gives an effect of pushing it down. You can further use this as an onclick image as shown below.

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/image">
        </item>
        <item android:drawable="@drawable/transparent_image">
        </item>
    </layer-list>
</item>
<item android:drawable="@drawable/image"></item>
</selector>

you have to use two images to do this.

  1. button_normal
  2. button_pressed

then create a xml resource in drawable folder

<?xml version="1.0" encoding="UTF-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

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

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

</selector>

then, set this file as a background for the imageview. here we are using imageview as button. dont forget to include those two buttons in the drawable folder. thats it.


It's possible to do with just one image file using the ColorFilter method. However, ColorFilter expects to work with ImageViews and not Buttons, so you have to transform your buttons into ImageViews. This isn't a problem if you're using images as your buttons anyway, but it's more annoying if you had text... Anyway, assuming you find a way around the problem with text, here's the code to use:

ImageView button = (ImageView) findViewById(R.id.button);
button.setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);

That applies a red overlay to the button (the color code is the hex code for fully opaque red - first two digits are transparency, then it's RR GG BB.).

You can make your ImageViews look like normal buttons by copying the btn_default_normal.9.png file from your sdkfolder/platforms/(android version/data/res/drawable to your own project. Then in your ImageView use android:background="@drawable/btn_normal_default" and android:src="..." to set an image inside the button.

Tags:

Android