Android Kotlin: ImageView set image from drawable

Introduction

In this Android Kotlin example, we will explore how to dynamically set an image in an ImageView using a drawable resource. This is a common task in Android development when dealing with images, such as icons, backgrounds, or illustrations, that need to be loaded from the app's resources folder. Understanding this process is crucial for building user interfaces that require dynamic or static image rendering.

The code provided is designed to be simple, making it ideal for developers who are getting familiar with Android's resource handling, particularly images stored in the drawable directory. This guide will break down the key components of the code, explain how it works, and clarify its purpose within the Android framework.

Code Breakdown

MainActivity.kt

The MainActivity.kt file contains the main logic for setting an image in an ImageView from a drawable resource. The activity extends AppCompatActivity, which is part of the AndroidX library, providing backward-compatible support for older Android versions. The onCreate method is overridden, which serves as the entry point when the activity is created. This is where the layout is inflated, and the logic to load and display the image is implemented.

To retrieve the image resource, the ContextCompat.getDrawable() method is used. This method takes the context (which is the current Activity) and the resource ID (R.drawable.flower) as arguments and returns a Drawable object. This approach ensures compatibility with older versions of Android, avoiding deprecated methods like getDrawable() directly from resources.

Once the drawable is retrieved, the apply function is called on it. The apply scope function allows us to use the this keyword to refer to the drawable object within its block. Inside this block, the setImageDrawable() method is used to set the drawable as the image of the ImageView component, which is referenced as imageView. This is a concise and Kotlin-friendly way to manipulate views in Android.

activity_main.xml

The activity_main.xml file defines the user interface, which includes an ImageView wrapped inside a ConstraintLayout. The ImageView has an ID @+id/imageView, which is used in the Kotlin code to reference the component and set the drawable. The layout defines constraints that position the ImageView within the parent layout, ensuring that the image is centered horizontally and located near the top of the screen.

Key attributes of the ImageView include layout_width set to 0dp and layout_height set to 250dp, which means that the width will be determined by the constraints and the height is fixed. A tools:srcCompat attribute is included, allowing previewing of a sample image in the layout editor but does not affect the actual app's runtime behavior.

Summary

This example demonstrates how to dynamically set an image in an ImageView using a drawable resource in Android Kotlin. By utilizing ContextCompat.getDrawable() for backward compatibility and Kotlin's scope functions like apply, the code efficiently sets the image in the ImageView component. The activity_main.xml layout file ensures proper positioning of the ImageView in the user interface.

Understanding how to load and manipulate images in Android is a key aspect of UI development. This simple example serves as a foundation for more advanced image handling techniques, such as loading images from external sources or manipulating images at runtime.


MainActivity.kt

package com.example.jetpack

import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_main.*


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

        // returns a drawable object associated with a particular resource id
        val drawable: Drawable? = ContextCompat
            .getDrawable(this,R.drawable.flower)

        // set the image view image from drawable
        drawable?.apply {
            imageView.setImageDrawable(this)
        }
    }
}
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">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="250dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials