Android ImageButton Using Kotlin With Example

In this article, we will learn about android ImageButton using Kotlin. We will go through various example that demonstrates how to use different attributes of ImageButton. For example,

In this article, we will get answer to questions like –

  • What is ImageButton?
  • Why should we consider ImageButton while designing ui for any app?
  • What are possibilities using ImageButton while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing Kotlin ImageButton Output Android ImageButton Using Kotlin

Tutorialwing Kotlin ImageButton Output

Getting Started

We can define android ImageButton widget as below –

ImageButton is a subclass of imageView that displays a button with image that can be clicked or pressed by user. By default, it acts as button. However, you can set image using android:src attribute.

Now, how do we use ImageButton in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as ImageButton. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android ImageButton Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using ImageButton in Kotlin

Follow steps below to use ImageButton in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">ImageButton</string>
        <string name="this_is_imagebutton">This is imageButton</string>
        <string name="image_button_clicked">You clicked imageButton</string>
    </resources>
    
  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?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">
    
        <ImageButton
            android:id="@+id/imageButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/this_is_imagebutton"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@mipmap/ic_launcher" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    In activity_main.xml file, we have defined imageButton widget. Notice the two attributes android:contentDescription and app:srcCompat . First one is being used to set an description to the image that will be shown when there is no image found. Second one is used to set image resource to the imageButton. Now, we will access this imageButton using kotlin file in the application.

  • We can also access it in Kotlin File, MainActivity.kt, as below –

    package com.tutorialwing.imagebutton
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.widget.Toast
    import com.tutorialwing.imagebutton.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    
    		setupClickListener()
    	}
    
    	private fun setupClickListener() {
    		binding.imageButton.setOnClickListener {
    			Toast.makeText(
    				this@MainActivity,
    				R.string.image_button_clicked,
    				Toast.LENGTH_SHORT
    			).show()
    		}
    	}
    }
    

    In MainActivity.kt file, we have accessed ImageButton widget. Then, we have set a click listener to it. On click, it will display a toast message.

Now, run the application. We will get output as below –

Tutorialwing Kotlin ImageButton Output Android ImageButton Using Kotlin

Tutorialwing Kotlin ImageButton Output

Different Attributes of ImageButton in XML

Now, we will see how to use different attributes of Android ImageButton using Kotlin to customise it –

Set Id of ImageButton

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of ImageButton using android:id attribute like below –

    <ImageButton
        android:id="@+id/imageButton_ID"
        />

Here, we have set id of ImageButton as imageButton_ID using android:id=”” attribute. So, if we need to reference this ImageButton, we need to use this id – imageButton_ID.
Learn to Set ID of ImageButton Dynamically

Set Width of ImageButton

We use android:layout_width=”” attribute to set width of ImageButton.
We can do it as below –

    <ImageButton
        android:id="@+id/imageButton_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of ImageButton Dynamically

Set Height of ImageButton

We use android:layout_height=”” attribute to set height of ImageButton.
We can do it as below –

    <ImageButton
        android:id="@+id/imageButton_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of ImageButton Dynamically

Set Padding of ImageButton

We use android:padding=”” attribute to set padding of ImageButton.
We can do it as below –

    <ImageButton
        android:id="@+id/imageButton_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in ImageButton using android:padding=”” attribute.
Learn to Set Padding of ImageButton Dynamically

Set Margin of ImageButton

We use android:layout_margin=”” attribute to set margin of ImageButton.
We can do it as below –

    <ImageButton
        android:id="@+id/imageButton_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in ImageButton using android:layout_margin=”” attribute.
Learn to Set Margin of ImageButton Dynamically

Set Background of ImageButton

We use android:background=”” attribute to set background of ImageButton.
We can do it as below –

    <ImageButton
        android:id="@+id/imageButton_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in ImageButton using android:background=”” attribute.
Learn to Set Background of ImageButton Dynamically

Set Visibility of ImageButton

We use android:visibility=”” attribute to set visibility of ImageButton.
We can do it as below –

    <ImageButton
        android:id="@+id/imageButton_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of ImageButton using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of ImageButton Dynamically

Till now, we have see how to use android ImageButton using Kotlin. We have also gone through different attributes of ImageButton to perform certain task. Let’s have a look at list of such attributes and it’s related task.

Different Attributes of Android ImageButton Widget

Below are the various attributes that are used to customise android ImageButton Widget. However, you can check the complete list of attributes of ImageButton in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –

Some of the popular attributes of imageButton inherited from imageView are –

Sr. XML Attributes Description
1 android:adjustViewBounds Responsible for auto adjust of view’s boundary to maintain the aspect ratio of it’s drawable.
2 android:baseline Defines offset of the baseline within this view.
3 android:baselineAlignBottom If true, it sets the baseline aligned with it’s bottom edge.
4 android:cropToPadding If true, image will be cropped to fit within it’s padding.
5 android:maxHeight Defines maximum height of the view.
6 android:maxWidth Defines maximum width of the view.
7 android:scaleType Specifies the way image will be resized or moved to match the size of the imageView
8 android:src Defines a drawable of the imageView
9 android:tint It tints the color of the image.
10 android:tintMode Specifies blending mode used to apply the image tint

Some of the popular attributes of ImageButton inherited from View are –

Sr. XML Attributes Description
1 android:alpha Defines alpha of the view
2 android:autofillHints Defines the data to be shown to auto fill in the view
3 android:background Defines background of the view
4 android:backgroundTint Defines tint to apply to the background
5 android:backgroundTintMode Specifies Blending mode used to apply the background tint
6 android:clickable Defines whether this view is clickable or not
7 android:elevation Specifies elevation to the view
8 android:fitsSystemWindows It is used to adjust view layout based on system windows
9 android:focusable Defines whether this view can take focus
10 android:id Defines unique id to the view
11 android:onClick Specifies what to do when this view is clicked
12 android:padding Defines padding to the view
13 android:tag Defines tag to the view
14 android:tooltipText Specifies tooltip text to be shown when hovered on the view
15 android:visibility Defines visibility of the view

We have seen different attributes of ImageButton and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is ImageButton, how can we use android ImageButton using Kotlin ? etc. We also went through different attributes of android ImageButton.