Set ImageView Image Programmatically
ImageView is a widget of Android native SDK. ImageView is a very popular element for android app developers. ImageView displays image resources in the android app user interface. ImageView displays images from various sources such as drawable resources and assets resources.
An Imageview can display various types of image resources, for example, bitmap and drawable resources.
ImageView also tints an image object and displays the result on its surface. ImageView widget also can scale an image resource. ImageView allows us to apply many types of scaling algorithms.
This android app development tutorial demonstrates how we can set an image to ImageView programmatically. Programmatically setting an image to ImageView means we have to add an image to ImageView by using a kotlin or java file.
To do this, at first we have to create an XML layout file and we will put an ImageView widget on it by using the Imageview tag and available attributes. Next, inside the java or kotlin file, we will use ImageView various methods to add an image to the ImageView widget.
Imageview setImageDrawable() method allows us to add a drawable resource to ImageView that acts as an image. ImageView setImageResource() method can help us to display an image on ImageView from the resource directory. ImageView setImageBitmap() method can directly display a bitmap image to ImageView widget.
This android app development tutorial also demonstrates how can we show an image to ImageView from an URL. We can also get an image object from the assets folder and display it on the ImageView surface. Even we can draw an image object and display it to the ImageView widget.
ImageView also tints an image object and displays the result on its surface. ImageView widget also can scale an image resource. ImageView allows us to apply many types of scaling algorithms.
This android app development tutorial demonstrates how we can set an image to ImageView programmatically. Programmatically setting an image to ImageView means we have to add an image to ImageView by using a kotlin or java file.
To do this, at first we have to create an XML layout file and we will put an ImageView widget on it by using the Imageview tag and available attributes. Next, inside the java or kotlin file, we will use ImageView various methods to add an image to the ImageView widget.
Imageview setImageDrawable() method allows us to add a drawable resource to ImageView that acts as an image. ImageView setImageResource() method can help us to display an image on ImageView from the resource directory. ImageView setImageBitmap() method can directly display a bitmap image to ImageView widget.
This android app development tutorial also demonstrates how can we show an image to ImageView from an URL. We can also get an image object from the assets folder and display it on the ImageView surface. Even we can draw an image object and display it to the ImageView widget.
MainActivity.kt
package com.cfsuman.kotlintutorials
import android.graphics.*
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import kotlinx.coroutines.*
import java.io.IOException
import java.net.URL
import kotlin.math.min
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Get the widgets reference from XML layout
val ivBitmap = findViewById<ImageView>(R.id.ivBitmap)
val ivDrawable = findViewById<ImageView>(R.id.ivDrawable)
val ivResource = findViewById<ImageView>(R.id.ivResource)
val ivAssets = findViewById<ImageView>(R.id.ivAssets)
val ivUrl = findViewById<ImageView>(R.id.ivUrl)
// Create a new bitmap and display it on image view
ivBitmap.setImageBitmap(
drawCircle(
color = Color.parseColor("#C5B358"),
radius = 300f,
canvasBackground = Color.parseColor("#C80815")
)
)
// Display an image on image view from drawable
ivDrawable.setImageDrawable(
ContextCompat.getDrawable(
applicationContext, // Context
R.drawable.gradient_rectangle // Drawable
)
)
// Display an image on image view from resource
ivResource.setImageResource(R.drawable.flower)
// Display an image into image view from assets folder
val assetsBitmap: Bitmap? = getBitmapFromAssets("flower100.jpg")
ivAssets.setImageBitmap(assetsBitmap)
// Display an image to image view from url
val url = URL("https://images.pexels.com/photos/954126/" +
"pexels-photo-954126.jpeg?auto=compress&cs=" +
"tinysrgb&dpr=2&h=750&w=1260")
urlToImageView(ivUrl,url)
}
// Custom method to get assets folder image as bitmap
private fun getBitmapFromAssets(fileName: String): Bitmap? {
return try {
BitmapFactory.decodeStream(assets.open(fileName))
} catch (e: IOException) {
e.printStackTrace()
null
}
}
// Method to draw a circle on a canvas and generate bitmap
private fun drawCircle(
color:Int = Color.LTGRAY,
bitmapWidth:Int = 1500,
bitmapHeight:Int = 750,
radius:Float = min(bitmapWidth, bitmapHeight) / 2f,
cx:Float = bitmapWidth / 2f,
cy:Float = bitmapHeight / 2f,
canvasBackground:Int = Color.WHITE
):Bitmap{
val bitmap = Bitmap.createBitmap(
bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888
)
// Canvas to draw circle
val canvas = Canvas(bitmap).apply {
drawColor(canvasBackground)
}
// Paint to draw on canvas
val paint = Paint().apply {
this.color = color
isAntiAlias = true
}
// Draw circle on canvas
canvas.drawCircle(
cx, // X-coordinate of the center of the circle
cy, // Y-coordinate of the center of the circle
radius, // Radius of the circle
paint // Paint used to draw the circle
)
return bitmap
}
// Method to show image on mage view from an url
private fun urlToImageView(imageView:ImageView,urlImage:URL){
// Async task to get bitmap from url
val result: Deferred<Bitmap?> = GlobalScope.async {
try {
BitmapFactory.decodeStream(urlImage.openStream())
}catch (e:IOException){
null
}
}
GlobalScope.launch(Dispatchers.Main) {
// Show bitmap on image view when available
imageView.setImageBitmap(result.await())
}
}
}
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"
android:id="@+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="24dp"
android:background="#DCDCDC">
<ImageView
android:id="@+id/ivBitmap"
android:layout_width="0dp"
android:layout_height="100dp"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<ImageView
android:id="@+id/ivDrawable"
android:layout_width="0dp"
android:layout_height="100dp"
android:scaleType="centerCrop"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/ivBitmap"/>
<ImageView
android:id="@+id/ivResource"
android:layout_width="0dp"
android:layout_height="100dp"
android:scaleType="centerCrop"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/ivDrawable"/>
<ImageView
android:id="@+id/ivAssets"
android:layout_width="0dp"
android:layout_height="100dp"
android:scaleType="centerCrop"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/ivResource"/>
<ImageView
android:id="@+id/ivUrl"
android:layout_width="0dp"
android:layout_height="100dp"
android:scaleType="centerCrop"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/ivAssets"/>
</androidx.constraintlayout.widget.ConstraintLayout>
res/drawable/gradient_rectangle.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<gradient
android:startColor="#ff6d6d"
android:centerColor="#69d14d"
android:endColor="#ffe02e"
android:angle="45"
/>
<corners android:radius="10dp"/>
</shape>
</item>
</selector>
build.gradle [app] [dependencies]
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1'

- kotlin - Toolbar example
- kotlin - Snackbar example
- kotlin - SwipeRefreshLayout example
- kotlin - Handler and Runnable example
- kotlin - Extension function example
- kotlin - NumberPicker example
- kotlin - Popup menu with icons example
- kotlin - Service example
- kotlin - Bottom navigation bar example
- kotlin - AsyncTask with cancel progress example