Wednesday, July 23, 2014

Use Image Button in Android

It happens many a times that we wish to use an image as a button in our Android app to enhance the user aesthetics. An easy way to do this is to use the Image Button. We can use “android.widget.ImageButton” to display a normal “Button“, with a customized background image for the button.

In this tutorial, we shall learn how to display a button with a background image named “imgbtn.png“. When a user clicks on it, a short toast message is displayed.

Note: We can also use ImageButton selector which allows to change a button’s images depending on whether the button is pressed or not. We shall see this in the next tutorial.

1. Add Image to Resources

Put the image you wish to use as the button background into “res/drawable-hdpi” folder, in our case "imgbtn.png".

2. Add ImageButton

Open the “res/layout/main.xml” file, add an “ImageButton” tag, and define the background image via “android:src“.

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:gravity="center"
android:orientation="vertical" >   <ImageButton android:id="@+id/imageButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/imgbtn" />   </LinearLayout>

3. Java Code

The Java code should look like this. Add a click listener on the image button.

File : Main.java

package com.endeavour.imagebuttontutorial;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
public class Main extends Activity {
       ImageButton imageButton;
       @Override
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              addListenerOnButton();
       }
       public void addListenerOnButton() {
              imageButton = (ImageButton) findViewById(R.id.imageButton1);
              imageButton.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View arg0) {
                        Toast.makeText(HomeScreen.this,"ImageButton is clicked!", Toast.LENGTH_SHORT).show();
                     }
              });
       }
}

4. Output

Run the program. The following output shall be produced, depending on the image that you have selected.

i. Image Button




ii. When Image Button is pressed



No comments:

Post a Comment