Dynamic ImageButton in Kotlin - GeeksforGeeks

28 Mar, 2022
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.
First we create a new project by following the below steps:
Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish.
Click on File, then New => New Project.
After that include the Kotlin support and click on next.
Select the minimum SDK as per convenience and click next button.
Then select the Empty activity => next => finish.
In this article, we will create the ImageButton programmatically in Kotlin file.
In this file, we will add only the EditText and set attributes for both of them to access into the Kotlin file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:id="@+id/linear_layout"    android:gravity="center">      <EditText        android:id="@+id/Num1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:ems="10"        android:hint= "Enter first number"/>      <EditText        android:id="@+id/Num2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:ems="10"        android:hint= "Enter second number"/>  </LinearLayout>
Modify the strings.xml file to write the name of the application
XML
<resources>    <string name="app_name">DynamicImageButtonInKotlin</string></resources>
We will declare a variable imgBtn to create ImageButton.
 val imgBtn = ImageButton(this)
then, set the image resource for the button using
imgBtn.setImageResource(R.drawable.ic_clear_black_24dp)
In the end, add the button into LinearLayout using
val linearLayout = findViewById(R.id.linear_layout)
  // Adding ImageButton in LinearLayout
  linearLayout.addView(imgBtn)

Other process similar to manually adding the Image Button in the layout.
Kotlin
package com.geeksforgeeks.myfirstkotlinapp  import android.os.Bundleimport android.view.ViewGroupimport androidx.appcompat.app.AppCompatActivityimport android.widget.EditTextimport android.widget.ImageButtonimport android.widget.LinearLayoutimport android.widget.Toast  class MainActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)        val num1 = findViewById<EditText>(R.id.Num1)        val num2 = findViewById<EditText>(R.id.Num2)        val imgBtn = ImageButton(this)        imgBtn.layoutParams = LinearLayout.LayoutParams(            ViewGroup.LayoutParams.WRAP_CONTENT,            ViewGroup.LayoutParams.WRAP_CONTENT)        imgBtn.setImageResource(R.drawable.ic_clear_black_24dp)            val linearLayout = findViewById<LinearLayout>(R.id.linear_layout)        // Adding ImageButton in LinearLayout        linearLayout.addView(imgBtn)          imgBtn.setOnClickListener {         if (num1.text.toString().isEmpty() || num2.text.toString().isEmpty()) {              Toast.makeText(applicationContext,                  "Enter both numbers", Toast.LENGTH_SHORT).show()            }            else {                val num1 = Integer.parseInt(num1.text.toString())                val num2 = Integer.parseInt(num2.text.toString())                Toast.makeText(applicationContext,                    "Multiplication of the numbers = " + (num1 * num2),                    Toast.LENGTH_SHORT).show()            }        }    }}
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp">  <application    android:allowBackup="true"    android:icon="@mipmap/ic_launcher"    android:label="@string/app_name"    android:roundIcon="@mipmap/ic_launcher_round"    android:supportsRtl="true"    android:theme="@style/AppTheme">    <activity android:name=".MainActivity">        <intent-filter>            <action android:name="android.intent.action.MAIN" />              <category android:name="android.intent.category.LAUNCHER" />        </intent-filter>    </activity></application>  </manifest>
 
ayushpandey3july
Android-Button
Kotlin Android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
Services in Android with Example
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Android UI Layouts
Kotlin Array
Services in Android with Example
Android RecyclerView in Kotlin