How to programmatically create ImageView in Android Kotlin

In this android kotlin source code example, we are going to programmatically create ImageView in Android Kotlin.

You can copy and adopt this source code example to your Kotlin android project without reinventing the wheel.

Below is a step by step source code to programmatically create ImageView in Android Kotlin.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".imageView.ImageViewActivity20">

</RelativeLayout>

MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import com.bluapp.kotlinview.R

class ImageViewActivity20 : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_image_view20)
        val relativeLayout = findViewById(R.id.relativeLayout) as RelativeLayout
        val relParam = RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        relParam.addRule(RelativeLayout.CENTER_IN_PARENT)
        relParam.setMargins(10, 10, 10, 10)
        val imageView = ImageView(this)
        imageView.setImageResource(R.drawable.profilepic)
        relativeLayout.addView(imageView, relParam)
    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment