Quantcast
Channel: Programming – Xinyustudio
Viewing all articles
Browse latest Browse all 284

Android Image Button: transparent background and custom pressed icon

$
0
0

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!


Filed under: Android Tagged: android, focused, image button, images, normal, pressed, tranparent background

Viewing all articles
Browse latest Browse all 284

Trending Articles