In this Kotlin code example we will learn how to create ImageView in Kotlin programmatically. The code example below will cover:
- Create ImageView in a ConstraintLayout
- Load picture from a resource and add it to the ImageView
For this example to work and to actually load an image, you will need to add at least one image into the /app/src/main/res/drawable folder in your project. In my case the name of the image is android_logo.png and it is inside of the drawable folder.
ImageView example in Kotlin
Please note that in the code below, when I set an image on the imageView with the setImageResource() function, I specify the name of the image I am loading by using the following format: R.id.<name of image file here>. Like so:
imageView.setImageResource(R.drawable.android_logo)
here is a complete code:
import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.constraint.ConstraintLayout import android.widget.ImageView class ImageViewExample : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_image_view_example) val constraintLayout = findViewById(R.id.constraintLayout) as ConstraintLayout val imageView = ImageView(this) imageView.setImageResource(R.drawable.android_logo) constraintLayout.addView(imageView) } }
Layout XML file
The following is the Activity_image_view_example.xml containing an empty ConstraintLayout to which we will add the ImageView.
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/constraintLayout" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.appsdeveloperblog.kotlin.examples.ImageViewExample"> </android.support.constraint.ConstraintLayout>
And this is it! If you run this example, with existing android_logo image in the drawable folder, you should see an image on the screen.
There are many more short code examples in Kotlin as well as longer step by step Kotlin tutorials available if you check the Android->Kotlin category of this blog.
And if you are looking for books or video tutorials on Kotlin check the list of resources below. I hope you will find some of them helpful!
Building Mobile Apps with Kotlin for Android – Books