Android ImageButton selector example

In last Android tutorial, you use “ImageButton” to display a “Button” with a customized background image easily. However, you can do more than that just a simple image, Android allow you to change the button’s image depends on different states like button is focused or button is pressed.

This example is referenced from this Android custom button article, with minor changes.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. Add Images to Resources

Prepare 3 images for button states, and put it into “resource/drawable” folder.

  1. button_normal_green.png – Default image button.
  2. button_focused_orange.png – Display when button is focused, for example, when phone’s keypad is move (focus) on this button.
  3. button_pressed_yellow.png – Display when button is pressed.

2. Add Selector for different button states

Now, create a new XML file in “res/drawable/” folder, in whatever name you want, in this case, we just give a name as “new_button.xml“. This file defined which button state is belong to which image.

Now, you can refer to this button via this Id : @drawable/new_button.

File : res/drawable/new_button.xml


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed_yellow"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_focused_orange"
          android:state_focused="true" />
    <item android:drawable="@drawable/button_normal_green" />
</selector>

3. Add Button

Open “res/layout/main.xml” file, add a normal button, and attach the background image to above “new_button” via “android:background="@drawable/new_button

File : res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/imageButtonSelector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/new_button" />
    
</LinearLayout>

4. Code Code

A normal button with a simple click listener.

File : MyAndroidAppActivity.java


package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;

public class MyAndroidAppActivity extends Activity {

	Button imageButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		addListenerOnButton();

	}

	public void addListenerOnButton() {

		imageButton = (Button) findViewById(R.id.imageButtonSelector);

		imageButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				Toast.makeText(MyAndroidAppActivity.this,
					"ImageButton (selector) is clicked!",
					Toast.LENGTH_SHORT).show();

			}

		});

	}

}

5. Demo

Run the application.

1. Result, default button. (button_normal_green.png)

normal button

2. Button is focused. (button_focused_orange.png)

button is focused

3. Button is pressed. (button_pressed_yellow.png)

button is pressed

Download Source Code

References

  1. Android custom button example
  2. Android ImageButton example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Indio John
Guest
Indio John

Thanks for explaining this so well, It really helps me in understanding basic android concepts of xml.

ponco robbi
Guest
ponco robbi

thanks!

Anand AnGryboyzz
Guest
Anand AnGryboyzz

Thanks for sharing this is Really helped me, ur explanation is very clear and u added the downloadable file thats add the advantage to rectify errors more accurately :) Good Work Keep Going

Ray
Guest
Ray
Nice, but I have a question about it. I would like to have a kind of state on this image button. I now have a toggle button like this. private OnClickListener powerButtonListener = new OnClickListener() { public void onClick(View arg0) { ToggleButton powerButton = (ToggleButton) arg0; if (D) Log.d(TAG, “powerButtonListener” + powerButton.isChecked()); searchAndConnect(); if (powerButton.isChecked()) { powerOn = 1; sendColorToArm(); } else { powerOn = 0; sendColorToArm(); if (mBTSerialService != null) mBTSerialService.stop(); } } }; (My image’s are in a xml file called on_btnaction.xml) in mainActivity.java. public class mainActivity extends Activity { ImageButton on_btnaction; @Override public void onCreate(Bundle savedInstanceState) {… Read more »
jl
Guest
jl

Thank you!!! It was so useful and well explained.

sizzatul manira
Guest
sizzatul manira

please help me button android app

Azlan Ibnu Kamisan
Guest
Azlan Ibnu Kamisan

Hi mkyong, How to code more than one Rollover button in one code,do you know it?

Ricky
Guest
Ricky

where is the coding for quick contact badge?

Nana
Guest
Nana

Hello, great tutorial. But what if I’m using imageview? Is the coding still the same?

trackback
How to set outer glow effect on click relativelayout in andriod? | Android Questions
prasanna
Guest
prasanna

state_focuse is not working even i download ur project run it’s also

jay
Guest
jay

Gud one tutorials really very helpfull……………:)

David Lindsley
Guest
David Lindsley

My app has a lot of buttons with images. Is there a way to recolor the “normal” bitmap (and preserve the transparency) to make a “selected” bitmap. Ive seen examples where the background is changed, but that only results in a big colored rectangle overlaying the image. It would be nice to do it on-the-fly so a “selected” icon would not need to be created ahead of time. Especially in the case where there are a lot of image buttons.

Nishant
Guest
Nishant

Good explanation

trackback
how to highlight a menu item on selection? : Android Community - For Application Development

[…] Use selector for costume buttons, search in google for more example. Here it it one […]

trackback
ImageAdapter with custom pressed buttons : Android Community - For Application Development
trackback
How to add a horizontal line to Button in Android? : Android Community - For Application Development

[…] folder which will select which image to choose based on the Button’s current state, check out here for more info on creating a selector for a button. It’s a decent amount of work, but […]

trackback
Android Followers » Android Tutorial From mkyong.com

[…] Android ImageButton selector example Use “Button” and “selector” tag to display buttons’ images depend on the button states. […]

Mark Capella
Guest
Mark Capella

Hello! I’m just getting started developing on the Android platform and your examples and such on this site are fantastic primers for me !

I’ve been working with Mozilla on Fennec, our Firefox version for mobile and decided it was time to do some native JAVA / app coding and this has been tremendously helpful getting me going.

fyi – I’m developing with intelliJ… It’s a fast, stable platform and all your examples work fantastic while using it.

Thanks you so much!

trackback
#Android como hacer un boton con una imagen « Action

[…] http://www.mkyong.com/android/android-imagebutton-selector-example/ Me gusta:Me gustaSe el primero en decir que te gusta. […]

jozzy
Guest
jozzy

Thx for the tutorial but i’ve got error on the part which say

@Override
public void onClick(View argO) {
// eclipse ask me to remove @Override

Jacek Milewski
Guest
Jacek Milewski

It works well only if You have fixed proportions of your button size. when You would try to scale button as its height would be twice as big as it is now – Your image will be streched :)

I have no idea how to do it well… still searching

Sher Ali
Guest
Sher Ali

Very Nice tutorials it is very helpful for beginners.

vijay kumar
Guest
vijay kumar

Thanks for that piece of information. I am calling rest service on pressing the button. But the problem is button color is changing after the rest call is finished(even though i am running the service on background thread using Runnable). Can it be possible to change the color instantly and after that perform the rest call.

Many Thanks,
vijay

David Johnston
Guest
David Johnston

So do you need to create a seperate xml for each button you are going to create like this?

trackback
Button color change on hover | PHP Developer Resource

[…] need to use what’s called a selector. You can read about them and get a tutorial from this site. Keep in mind that there really isn’t a concept in Android as “hover” since you […]

trackback
How to show that ImageButton is pressed? | PHP Developer Resource

[…] should use a selector for choosing all the different appearances of a UI element, including an […]

trackback
Change appearance of button/imageview/imagebutton in android in different states « Say hello to python!

[…] pressed-state. ( I used these, and don’t care about others ). I find an interesting post at http://www.mkyong.com/android/android-imagebutton-selector-example/ Just re-post in my blog for later use. Step 1 : Add images to resource. button_normal_green.png – […]

Chirag Desai
Guest
Chirag Desai

Thanks for share this…its really helpful for fresher android developer…

rtrtrt
Guest
rtrtrt

good

trackback
Android button example

[…] Note For more advance function, like image, please refer to this ImageButton example and also this ImageButton selector example.1. Add ButtonOpen “res/layout/main.xml” file, add a button. […]