Android ImageButton - Set Image to ImageButton

Sometimes we need to use an image and add click/tap events on that image like Button widget. To do this we have a widget in Android called ImageButton. In this chapter we are going imlement add Image to ImageButton and add tap/click events.

  • Create a ImageButton
  • Set Image to ImageButton
  • Scale Image with Large and Small image
  • Show Toast message on ImageButton click

 

Create a ImageButton

Create a Project in Android studio (File->New->New Project) choose Empty Activity template and finish all basic setup Open xml file, you will see default Textview in the file Now drag and drop Button widget from Pallet windowSample code for button inside xml file would be like this

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

ImageButton image settings

Add image to drawable folder which you want set to ImageButton. To set image we have two ways

set as background

<ImageButton
    ...
    android:background="@drawable/image" />

 

android:src

set as source using android:src attribute

<ImageButton
    ...
    android:src="@drawable/image" />

 

If you specify an image with src, you will see light gray bounds around the image. If you set a transparent color for the background,will not be visible

android:background=”#0000″

 

Set image to ImageButton Android



Add Big image as Background, it will cover the entire space  Now set the same as source then that image will not properly set, it might be scale and not shown complete image.

Set image to ImageButton Android

To show image properly we need to set the scaleType attibute with respected values

 

Image ScaleTypes in Android

centerInside : Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding). The image is then centered in the view                 
centerCrop: Scale the image uniformly (maintain the image's aspect ratio) so both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). The image is then centered in the view
center: Center the image in the view, but perform no scaling
fitCenter: Scale the image using {@link android.graphics.Matrix.ScaleToFit#CENTER}
fitXY: Scale the image using {@link android.graphics.Matrix.ScaleToFit#FILL}

 

Set image to ImageButton Android

 

Access Button inside activity class

We defined button in xml file and now we need to access that button inside activity class. To access this we will use the id attribute of the button and initialize it by using the findViewById() method

Kotlin code:

val imageButton=findViewById<ImageButton>(R.id.imageButton)


       
Java Code:

Button imageButton=findViewById(R.id.imageButton);


       
       

ImageButton OnClick
 If user click on a ImageButton then Button object receive on-click event. To perform an event on the button, we will add "android:onClick" attribute to the <ImageButton> element in XML layout.

Now we need to create a method with the same inside activity file to handle the click event. The Activity hosting the layout must then implement the corresponding method.

For example – layout with a button using android:onClick

<ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:background="#0000"
        android:src="@drawable/am"
        android:onClick="clickme" />

 

The "likeme" method will be looks like below in activity file

Kotlin Code

fun clickme(view: View) {
    Toast.makeText(applicationContext,"Clicked",Toast.LENGTH_SHORT).show()
    }

 

Java Code

public void clickme(View view)
    {
        Toast.makeText(getApplicationContext(),"Clicked", Toast.LENGTH_SHORT).show()
    }

 

ImageButton onClickListener

To handle the button event programmatically we will add "onClickListener" event to the button using setOnClickListener() method

Kotlin Code:

imageButton.setOnClickListener {

        }

 

Java Code:

imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                
            }
        });

Complete code for Android ImageButton


xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:background="#0000"
        android:src="@drawable/am"
        android:onClick="clickme"
        android:scaleType="centerInside"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

MainActivity.kt file

package com.example.emptyactivity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ImageButton
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val imageButton=findViewById<ImageButton>(R.id.imageButton)
        imageButton.setOnClickListener {
            Toast.makeText(applicationContext,"Clicked", Toast.LENGTH_SHORT).show()
        }
    }

    fun clickme(view: View) {
        Toast.makeText(applicationContext,"Clicked2",Toast.LENGTH_SHORT).show()
    }
}

 

Conclusion:
In addition to ImageButton, there also possible to set an image to the Button to make the image look like a button, but from Android Studio 4, the background color remains attached to the Button, making it difficult to change the background. But we can add Image to the button using drawble attributes like drawableLeft,drawableRight,drawableTop,drawableBottom. You can read about android button at the link
 

Android compose button examples

Set Button height and Width with Jetpack Compose example

Change button text and color programatically with Android Compose

Compose Button click event listener

Create Gradient buttons with Android compose