RSS

Android Image Button: transparent background and custom pressed icon

30 Jul

In android app development, image button with transparent background is frequently used. The most easy way to have a transparent background is to use the “@null” value for the background.

<ImageView
android:id=”@+id/imageView1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_gravity=”center|bottom”
android:adjustViewBounds=”true”
android:background=”@null”
     android:src=”@drawable/tools” />

image tool1

android:background=”@null”

Easy! But when you run your app, you will find when the ImageButton is pressed, there is no visual clue showing that it is indeed pressed. What we want is, for example, use a background color to indicate it is pressed, or better, use separate images for normal, focused and pressed state. To do that:

  • delete the android:src=”…”;
  • delete the android:background=”@null”;
  • add android:background=”@drawable/tools_selector”
<ImageView
android:id=”@+id/imageView1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_gravity=”center|bottom”
android:adjustViewBounds=”true”
     android:background=”@drawable/tools_selector”

     android:background=”@null”
     android:src=”@drawable/tools” />

tool1 tool2

normal and pressed images

Now, we need create a new drawable, called tools_selector (any name will do, but should be consistent with the xml you used), in which you can specify the normal, focused and pressed images:

<?xml version=”1.0″ encoding=”utf-8″?>
<selector xmlns:android=”http://schemas.android.com/apk/res/android”>
<item android:drawable=”@drawable/tools_pressed” android:state_pressed=”true”/>
<item android:drawable=”@drawable/tools_normal“/>
<!– <item android:drawable=”@drawable/tools_focused” android:state_focused=”true”/> –>
</selector>
 drawable/tools_selector.xml

Note that you don’t need to provide all the normal, pressed and focused images here, for instance the focused image is commented out.

That is it. Now build and run, you will see the visual feedback when an image button is pressed!

Advertisements
 
2 Comments

Posted by on July 30, 2013 in Android

 

Tags: , , , , , ,

2 responses to “Android Image Button: transparent background and custom pressed icon

  1. androidappssite

    July 31, 2013 at 2:01 am

    Reblogged this on Android apps and commented:
    Don’t forget Max Battery Booster: https://play.google.com/store/apps/details?id=com.faygroup.maxbatterybooster

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: