VOOZH about

URL: https://www.geeksforgeeks.org/kotlin/imagebutton-in-kotlin/

⇱ ImageButton in Kotlin - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

ImageButton in Kotlin

Last Updated : 29 Jan, 2025

Android ImageButton is a user interface widget which is used to display a button having image and to perform exactly like button when we click on it but here, we add an image on Image button instead of text. There are different types of buttons available in android like ImageButton, ToggleButton, etc. We can add an image to the button simply by using attribute android:src in activity_main.xml file or by using setImageResource() method.

In android, we can create ImageButton control in two ways either manually or programmatically.

Different attributes of Switch widget

XML AttributesDescription
android:idUsed to uniquely identify the control.
android:srcUsed to specify the source file of the image.
android:onClickUsed to Specifies what to do when this button is clicked.
android:visibilityUsed to set visibility of the image button.
android:backgroundUsed to set background color of the Image button.
android:maxHeightUsed to set maximum height of the Image button view.
android:maxWidthUsed to set maximum width of the Image button view.
android:paddingUsed to set the padding from left, right, top and bottom.

Step by Step Implementation of ImageButton

Let us check a example implementing the ImageButton in Android.

Step 1: Create New Project

First we create a new project by following the below steps:

  1. Click on File, then New => New Project.
  2. After that include the Kotlin support and click on next.
  3. Select the minimum SDK as per convenience and click next button.
  4. Then select the Empty activity => next => finish.

Step 2: Use ImageButton in activity_main.xml file

In this file, we include the Edittext and ImageButton and set their attributes like id, layout_width, hint etc.

activity_main.xml:

Layout:

👁 Layout_ImageView


Step 3: Access ImageButton and EditText in MainActivity.kt file

First of all, we declare two variables num1 and num2 for both edittext and access them using the ids.

val num1 = findViewById(R.id.Num1)
val num2 = findViewById(R.id.Num2)

then, we declare variable imgbtn for the ImageButton and set the OnCLickListener to check the filled is empty or not

val imgbtn = findViewById(R.id.imageBtn)
imgbtn.setOnClickListener {
if (num1.text.toString().isEmpty() || num2.text.toString().isEmpty()) {
Toast.makeText(applicationContext,
"Enter both numbers", Toast.LENGTH_SHORT).show()
}

MainActivity.kt:

Output:

👁 ImageButton


Comment
Article Tags:

Explore