Sunday, August 23, 2020

android kotlin - Create ImageView programmatically

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" />