Android Image Button

In this tutorial, we show you how to display a button with a background image.

1. Add Image to Resources
Put the  images into “res/drawable-?dpi” folder. So that Android know where to find your image.
2. Add ImageButton
Open “res/layout/main.xml” file, add a “ImageButton” tag, and defined the background image via “android:src“. (see the code snippet below)



Open main xml under the res/layout folder
Code snippet


<?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"
    android:fitsSystemWindows="true"
    android:background="@color/bcolor" >
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="horizontal" >
    <ImageButton
        android:layout_width="156dp"
        android:layout_height="156dp"
        android:src="@drawable/cupcake_info"
        android:background="@color/bcolor1" />

    <ImageButton
        android:layout_width="156dp"
        android:layout_height="156dp"
        android:src="@drawable/cupcake_cancel"
        android:background="@color/bcolor3" />
</LinearLayout>
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="horizontal" >
    <ImageButton
        android:layout_width="156dp"
        android:layout_height="156dp"
        android:src="@drawable/cupcake_clock"
        android:background="@color/bcolor4" />

    <ImageButton
        android:layout_width="156dp"
        android:layout_height="156dp"
        android:src="@drawable/cupcake_help"
        android:background="@color/bcolor2" />
</LinearLayout>
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="horizontal" >
    <ImageButton
        android:layout_width="156dp"
        android:layout_height="156dp"
        android:src="@drawable/cupcake_lock_open"
        android:background="@color/bcolor5" />

    <ImageButton
        android:layout_width="156dp"
        android:layout_height="156dp"
        android:src="@drawable/cupcake_close"
        android:background="@color/bcolor6" />
</LinearLayout>
<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Joemel E. Resare, MIT"
        android:textSize="20dp"
    />
</LinearLayout>