Home » Android

Android ImageButton Example Code



In this tutorial, we are going to learn about ImageButton in android i.e. How to display an image on a button? As you click on the image button a toast message is displayed.
Submitted by Shamikh Faraz, on MAY 05, 2018

1) XML File: activity_main

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.faraz.imagebutton_example.MainActivity">

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/finger"
        tools:layout_editor_absoluteX="130dp"
        tools:layout_editor_absoluteY="155dp" />
</android.support.constraint.ConstraintLayout>

2) File: MainActivity.java

package com.example.faraz.imagebutton_example;

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

    ImageButton imageButton;

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

        addListenerOnButton();

    }

    public void addListenerOnButton() {

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

        imageButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Toast.makeText(MainActivity.this, "You Clicked Image Button!", Toast.LENGTH_LONG).show();

            }

        });

    }

}

Note: Remember image button size should be 100dp and 50dp. You can resize it, but should not be very large.

Output

After executing your code, you get an image. Actually this is not only an image, but a button containing an image. As you click on the image button a toast message is displayed as “You Clicked Image Button”.

Output - Android ImageButton Example Code 1
Output - Android ImageButton Example Code 2






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.