How to add loading animation in an ImageView in Android Studio [Kotlin]

Tutorial to add preloader before the actual image from web is loaded.

Table of contents

No heading

No headings in the article.

Often, we display images from a web URL in our android applications. Executing it in an effectively modern way will always help boost productivity, developer satisfaction, and code safety.

To use an image from web in android, it has to be internally stored and then decoded from the same. This blog will walk you through adding a custom loader while the image from the URL loads and also displaying an error image in case there's a network disconnectivity.

COIL(Coroutine Image Loader) library is used in steps mentioned below which is optimized better for Modern Android Development Skills in Kotlin. Created in 2019, it also uses modern libraries including Coroutines, OkHttp, Okio, and AndroidX Lifecycles.

There are other libraries such as Glide/Picasso/UIL etc. as well but COIL works better in terms of CPU performance, loading and caching as an in-memory cache, a storage-based cache, or both while working in low-priority background threads so the UI remains responsive. If you're migrating from Glide/Picasso library to coil, you can refer to the link here .

Step 1: Create a new project in Android Studio and select an empty activity. Version Used for this: Android Studio Arctic Fox 2020.3.1

Screenshot 2022-01-18 151233.jpg

Screenshot 2022-01-18 151151.jpg

Step 2: Add the internet permission in AndroidManifest.xml

    <uses-permission android:name="android.permission.INTERNET" />

image.png

Step 3: Add the coil dependency. Always add the updated version referring to this link

Coil is available on mavenCentral(). So, make sure mavenCentral() is in build.gradle(project) file.

image.png

Next add in the dependencies in build.gradle(module) file.

dependencies {
// Coil
implementation "io.coil-kt:coil:1.4.0"
}

Step 4: Remove the textView from activity_main.xml and add an ImageView in its place with proper constraints.

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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="417dp"
        android:layout_height="439dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/backgrounds/scenic" />
</androidx.constraintlayout.widget.ConstraintLayout>

Step 5: We may use the default way as given in MainActivity.kt to link its xml file or we can use ViewBinding. To use viewbinding , it must be declared true in build.gradle(project) file.

image.png

In the MainActivity.kt after the super.onCreate(savedInstanceState) line add

var binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

Step 6: In the last step, we will load the image on the ImageView. Add the image/gif which you want to display in the Drawables folder in res or through ResourceManager. Here loading_animation and broken_image is used. Add the following in MainActivity.kt

binding.imageView.load("https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg") {
            crossfade(true)
            placeholder(R.drawable.loading_animation)
            error(R.drawable.ic_broken_image)
            transformations(CircleCropTransformation())
        }
  • Crossfade is for smooth transformation.
  • Placeholders are Drawables that are shown while a request is in progress.
  • Error Drawables are shown when a request permanently fails.
  • The transformations method makes the image round.

You can use the drawables mentioned here through the github link provided below.

MainActivity.kt

package com.example.demoproject

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import coil.load
import coil.transform.CircleCropTransformation
import com.example.demoproject.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        var binding = ActivityMainBinding.inflate(layoutInflater)
        val view= binding.root
        setContentView(view)

        binding.imageView.load("https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg") {
            crossfade(true)
            placeholder(R.drawable.loading_animation)
            error(R.drawable.ic_broken_image)
            transformations(CircleCropTransformation())
        }
    }
}

Final Output is displayed as:

When image is loading

via GIPHY

When network isn't there, a broken link image will be displayed.

The github repo for this demo is this.

Feel free to add suggestions.