Android Kotlin: How to create an ImageView programmatically

Introduction

This code demonstrates how to programmatically create an ImageView and add it to a ConstraintLayout in Android. An ImageView is a fundamental view for displaying images and can be used in various layouts.

Explanation

  1. Import Statements: The code begins by importing essential libraries like Context, android.graphics, Bundle, View, ImageView, AppCompatActivity, ConstraintLayout, etc. These libraries provide the functionalities used throughout the program.

  2. MainActivity Class: The MainActivity class inherits from AppCompatActivity, which serves as the foundation class for most activities in Android. The onCreate() method acts as the entry point of the activity and is invoked when the activity is first created.

  3. Create ImageView Programmatically: Inside the onCreate() method, an ImageView is constructed programmatically using the applicationContext.createImageView() extension function. This function generates an ImageView instance, sets its layout parameters, and assigns it an id.

  4. Add ImageView to ConstraintLayout: The newly created ImageView is then incorporated into the constraint layout using the constraintLayout.addViewTop(context, view) extension function. This function not only adds the view but also establishes constraints using ConstraintSet to position the ImageView at the top of the parent layout with a 10dp margin and centered horizontally.

  5. Set Image from Assets: The setImageBitmap(assetsToBitmap("flowers5.jpg")) method is employed to set the image from the assets folder. The assetsToBitmap() extension function retrieves the specified image file from the assets folder and converts it into a Bitmap object.

  6. Set Image Scale Type: The adjustViewBounds property is set to true, and the scaleType property is set to ImageView.ScaleType.CENTER_CROP to guarantee that the image is displayed within the ImageView's boundaries.

  7. Extension Functions: The code also defines three extension functions: createImageView(), addViewTop(), and assetsToBitmap(). These functions enhance code readability and reusability.

Summary

This code example showcases how to programmatically create an ImageView, add it to a ConstraintLayout, and display an image from the assets folder. By leveraging extension functions, the code maintains readability and promotes reusability.

Table of Extension Functions

Function NameDescription
createImageView()Creates an ImageView programmatically, sets its layout parameters, and assigns it an id.
addViewTop(context, view)Adds a view to the top of a ConstraintLayout and sets constraints to position it.
assetsToBitmap(fileName)Retrieves an image from the assets folder and converts it into a Bitmap object.


MainActivity.kt


package com.example.jetpack

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams.PARENT_ID
import androidx.constraintlayout.widget.ConstraintSet
import kotlinx.android.synthetic.main.activity_main.*
import java.io.IOException


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // create an image view programmatically and add to layout
        applicationContext.createImageView().apply {
            // add image view to constraint layout
            constraintLayout.addViewTop(applicationContext,this)

            // get bitmap from assets folder
            setImageBitmap(assetsToBitmap("flowers5.jpg"))

            // set image scale type
            adjustViewBounds = true
            scaleType = ImageView.ScaleType.CENTER_CROP
        }
    }
}


// extension function to create an image view programmatically
fun Context.createImageView(): ImageView {
    return ImageView(this).apply {
        layoutParams = ConstraintLayout.LayoutParams(
            ConstraintLayout.LayoutParams.MATCH_PARENT, // width
            //ConstraintLayout.LayoutParams.WRAP_CONTENT // height
            285.dpToPixels(context) // height
        )

        id = View.generateViewId()
    }
}


// extension function to add view top of constraint layout
fun ConstraintLayout.addViewTop(context: Context, view: View){
    addView(view)

    val set = ConstraintSet()
    set.clone(this)

    // connect view start with parent start
    set.connect(
        view.id,ConstraintSet.START,
        PARENT_ID,ConstraintSet.START,
        5.dpToPixels(context) // margin
    )

    // connect view top with parent top
    set.connect(
        view.id, ConstraintSet.TOP,
        PARENT_ID,ConstraintSet.TOP,
        10.dpToPixels(context) // margin
    )

    // connect view end with parent end
    set.connect(
        view.id, ConstraintSet.END,
        PARENT_ID,ConstraintSet.END,
        5.dpToPixels(context) // margin
    )

    set.applyTo(this)
}


// extension function to get bitmap from assets
fun Context.assetsToBitmap(fileName: String): Bitmap?{
    return try {
        with(assets.open(fileName)){
            BitmapFactory.decodeStream(this)
        }
    } catch (e: IOException) { null }
}


// extension function to convert dp to equivalent pixels
fun Int.dpToPixels(context: Context):Int = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), context.resources.displayMetrics
).toInt()
activity_main.xml

<?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:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EDEAE0"
    tools:context=".MainActivity" />
More android kotlin tutorials