Ilias Tsagklis

About Ilias Tsagklis

Ilias Tsagklis is a senior software engineer working in the telecom domain. He is an applications developer in a wide variety of applications/services. Ilias is co-founder and Executive Editor at Java Code Geeks.

Android ImageButton Selector Example

In Android you can use the ImageButton component to display a normal Button with a custom image as a background. Take a look at our previous tutorial to remember the use of ImageButton. The fact is that you can do more than just an Image which is also a button. In this tutorial we are going to use two different images that will reflect the status of one button. When the button is released, the green Android logo will be the background image of the button. When the button is pressed, the green Android logo will be the background image of the button.
 
 
 
 
 
For this tutorial, we will use the following tools in a Windows 64-bit platform:

  1. JDK 1.7
  2. Eclipse 4.2 Juno
  3. Android SKD 4.2

1. Create a new Android Project

Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project and click Next.

You have to specify the Application Name, the Project Name and the Package name in the appropriate text fields and then click Next.

In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.

Select “BlankActivity” and click Next.

You will be asked to specify some information about the new activity.  In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml will be created. Then, click Finish.

2. Adding a picture in the appropriate project folder 

As you would have noticed in the Package explorer, there are 4 folders that contain the image resources of the project :

  1. res/drawable-hdpi
  2. res/drawable-ldpi
  3. res/drawable-mdpi
  4. res/drawable-hdpi

You can copy the images you want to put in you’re application in any one of these folders.  Android SDK will automatically recognize any images you put on any one of these folders as drawable resources. So, copy the images in the folder you want. If the image does not appear in the Package Explorer under the folder you’ve copied it into, right click on the project name and select Refresh. Now the image should be under the correct folder. As you can see, I’ve three images in res/drawable-hdpi:

3. Create the Selector for different button states

We want to use the Selector component as a drawable resource in our main.xml file. Right click on the res/drawable-hdpi folder and select New -> Other -> Android -> Android XML File:

And provide the requested attributes as shown in the picture below, and Click Finish:

As you will notice, on the Package Explorer a new folder has been created (res/drawable) that contains mybutton.xml:

So now mybutton.xml is a drawable resource. Open that file and paste the following code:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

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

</selector>

4. Create the main layout of the Application

Open res/layout/main.xml file :

And paste the following code :

<?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/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:background="@drawable/mybutton" />

</LinearLayout>

Now you may open the Graphical layout editor to preview the User Interface you created:

5. Code

Go to the java file that contains the code of the activity you’ve just created:

And paste the following code:

package com.javacodegeeks.android.imagebuttonselectorexample;

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 MainActivity extends Activity {

	Button button;

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

		addButtonListener();

	}

	public void addButtonListener() {

		button = (Button) findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				Toast.makeText(MainActivity.this,"Button is clicked!",Toast.LENGTH_SHORT).show();
			}
		});
	}
}

The above code is pretty straight forward. When we press the image button, a short message will be displayed.

6. Run the application

This is the main screen of our Application. Remember that the image is also a button:

Now, when you press the button and keep it pressed:

When you leave the button :

Download Eclipse Project

This was an Android ImageButton Selector Example. Download the Eclipse Project of this tutorial: AndroidImageButtonSelectorExample.zip

Related Whitepaper:

Beginning Android Application Development (Free Sample Chapter)

Create must-have applications for the latest Android OS!

The Android OS is a popular and flexible platform for many of today's most in-demand mobile devices. This full-color guide offers you a hands-on introduction to creating Android applications for the latest mobile devices. Veteran author Wei Meng Lee accompanies each lesson with real-world examples to drive home the content he covers. Beginning with an overview of core Android features and tools, he moves at a steady pace while teaching everything you need to know to successfully develop your own Android applications.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books