Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

How to make button show it is clicked (by setting it go down/some change) for buttons using custom background image in Android. I do not want to include more images and set different one to different states like shown in google hello views example. Thanks.

like image 820
Pritam Avatar asked Apr 16 '10 06:04

Pritam


Video Answer


2 Answers

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.

like image 180
Praveen Avatar answered Sep 23 '22 14:09

Praveen


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.

like image 45
Steve Haley Avatar answered Sep 21 '22 14:09

Steve Haley