Android ImageButton Example

By | October 24, 2013
To Create a Image Button Android SDK Provides “android.widget.ImageButton” class ,displays a image instead of text that can be clickable by the user

In this tutorial we will see how to add imagebutton component to the activity and also set the onclicklistener for it to display the toast message.

Android Image ButtonAndroid Image Button onClick


Lets See An Example

Project Detail

Project Name ImageButton
Package com.example.imagebutton
Minimum SDK API 8
Target SDK API 17
Theme Holo Light with Dark Action Bar

 1. XML Layout

file :- activity_main.xml

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

<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:layout_gravity="center" />

</LinearLayout>

 2. Activity

file :- MainActivity.java

package com.pavan.imagebutton;

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

public class MainActivity extends Activity {

ImageButton image_btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

image_btn = (ImageButton) findViewById(R.id.imageButton1);

image_btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

Toast.makeText(MainActivity.this,
"You clicked On Image Button", Toast.LENGTH_SHORT)
.show();

}
});

}
}