How to Show Placeholder Image in Android Jetpack Compose
In mobile app development, a placeholder image is used as a temporary representation of content that has yet to be loaded. This could be an image that is being loaded from a remote source, or it could be a temporary image that is displayed while the app is loading data.
Placeholder image improves the user experience by giving users immediate feedback that something is happening while they wait for the actual content to load. In this blog post, let’s check how to add a placeholder image while the real image is loading from the internet in Jetpack Compose.
Here, we use the Coil library for loading images asynchronously. Open the build.gradle of the app module and add the following code to the dependencies tag.
implementation("io.coil-kt:coil-compose:2.2.2")
Remember to add internet permission in the Android Manifest file.
<uses-permission android:name="android.permission.INTERNET" />
You can add the placeholder image as given below.
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data("https://cdn.pixabay.com/photo/2016/07/16/03/50/pigs-1520968_1280.jpg")
.crossfade(true)
.build(),
placeholder = painterResource(R.drawable.avatar),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.size(300.dp)
)
Following is the complete code for reference.
package com.example.myapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.myapplication.ui.theme.MyApplicationTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ImageExample()
}
}
}
}
}
@Composable
fun ImageExample() {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data("https://cdn.pixabay.com/photo/2016/07/16/03/50/pigs-1520968_1280.jpg")
.crossfade(true)
.build(),
placeholder = painterResource(R.drawable.avatar),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.size(300.dp)
)
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MyApplicationTheme {
ImageExample()
}
}
That’s how you display a placeholder image in Jetpack Compose.