Android ImageView Using Kotlin

android imageview kotlin example
Android ImageView

Read later
Save important notes and articles from internet using arusaquotes app.

Create Project

Open Android Studio and create a new project. Give the project name ImageView.

Adding image in drawable XML

First of all, find the image in your machine. Copy the image. Open android studio, go to app > res > drawable and paste your copied image. You have inserte the picture in drawable successfully. Now you can use the image in your project.

XML Code

Go to app > resource > layout > activity_main.xml. Add an imageview. Now set the image in imageview using following xml attribute.

android:src="@drawable/notesjam"

If your image width is greater than the device width, you should use the following attribute to fix the problem.

android:adjustViewBounds="true"

Here is the final xml code of activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/logoImg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="28dp"
        android:adjustViewBounds="true"
        android:contentDescription="@string/logo"
        android:src="@drawable/notesjam" />

</androidx.appcompat.widget.LinearLayoutCompat>

Kotlin Code

Go to app > java > com.example.imageview > MainActivity.kt and put the following code after initializing imageview.

//on click listener on imageview
        logoImg.setOnClickListener {
            Toast.makeText(this, "Image clicked", Toast.LENGTH_LONG).show()
        }

For setting image in imageview programmatically using Kotlin, use the following code.

//Set image in imageview programmatically
        logoImg.setImageResource(R.drawable.notesjam)

Here is the final Kotlin code MainActivity.kt

package com.example.imageview

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    private lateinit var logoImg: ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        logoImg = findViewById(R.id.logoImg)

        //on click listener on imageview
        logoImg.setOnClickListener {
            Toast.makeText(this, "Image clicked", Toast.LENGTH_LONG).show()
        }

        //Set image in imageview programmatically
        logoImg.setImageResource(R.drawable.notesjam)
    }
}

Output

Here is the final output.

android imageview kotlin
Android ImageView

Learn Android App Development using Kotlin.

Start Learning