VOOZH about

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

⇱ Dynamic ImageButton in Kotlin - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Dynamic ImageButton in Kotlin

Last Updated : 12 Jul, 2025

An ImageButton in Android is a specialized Button that displays an image instead of text while functioning like a regular button. When clicked, it triggers an action just like a standard button. Android provides various button types, including ImageButton, ToggleButton, and more. To set an image on an ImageButton, you can use the android:src attribute in the XML layout file or the setImageResource() method in the Kotlin code.

You can create an ImageButton in Android using two approaches:

  1. XML Layout: Define it in the activity's XML file.
  2. Programmatically: Create and configure it in the Kotlin file.

In this article, we will create an ImageButton programmatically using Kotlin.

Step by Step Implementation

Step 1: Create a new project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Step 2: Use LinearLayout in activity_main.xml file

In this file, we will add only the EditText and set attributes for both of them to access into the Kotlin file.

activity_main.xml:

Design UI:

👁 dynamic-image-button


Step 3: Create Image Button in MainActivity.kt file

We will declare a variable imageButton to create ImageButton.

val imageButton = ImageButton(this)
imageButton.layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)

then, set the image resource for the button using

imageButton.setImageResource(android.R.drawable.ic_menu_close_clear_cancel)

In the end, add the button into LinearLayout using

val linearLayout: LinearLayout = findViewById(R.id.main)
linearLayout.addView(imageButton)

Other process similar to manually adding the Image Button in the layout.

MainActivity.kt

Output:

Comment
Article Tags:

Explore