How to load and display an image from a URL using Jetpack Compose and Kotlin
A step by step guide on loading an image from a URL and displaying it in an Android app using Jetpack Compose and Kotlin.
The following tutorial builds on our Open Source Kotlin project which can be downloaded using the link below, and aims to walk you through how to setup an Android project to load images from a URL and place them in an Android app using Jetpack Compose.
We recommend that you checkout the main branch and carry out the steps described below. The changes that took place can be found on the tutorial/data/image-from-url branch.
git clone git@github.com:delasign/kotlin-android-starter-project.git
Step One: Add Internet Permissions
In the projects AndroidManifest.xml file, add the following permission:
<uses-permission android:name="android.permission.INTERNET" />
Step Two: Add the Dependency
In the App Level build.gradle.kts file, add the following dependency:
implementation("io.coil-kt:coil-compose:2.4.0")
Please note that versions displayed above may not be the latest versions, please update the code above to the latest version in your Android Studio project.
Step Three: Sync the Gradles
Press Sync Now in the bar above the Gradle to update the project dependencies.
Step Four: Load and Display the Image
Load and display the image in a composable, using code similar to that below:
Please note that the placeholder drawable is what's shown when the image is loading and the error drawable is what gets drawn if the image does not load.
If you wish to create a loading indicator use the onLoading, onSuccess and onError listeners along with mutable states, modifiers and more complex Composable visual logic to show the indicator whilst the image is loading.
Please note that it is suggest that you localize your images to ensure that they can be read by people with dissabilities.
Step Five: Test
Run the app to check that the image loads correctly.