Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use image placeholders for preview with Jetpack Compose

With XML, we had the option to use tools: for designing by using placeholders when real data is not available. Do we have something similar in Jetpack Compose?

I know I can pass sample data to my composable in a dedicated preview function. But for instance, when an image source is a URL (that loads by Coil, Glide.. ), even if I pass a sample URL, it can't be loaded in preview. A practical solution for that could save development time.

like image 465
Oya Canli Avatar asked Sep 03 '25 09:09

Oya Canli


2 Answers

2022 November update

If you are using Coil...

implementation("io.coil-kt:coil-compose:2.2.2")

... now you can preview with a placeholder in debug mode only this way:

AsyncImage(
   model = "https://www.example.com/image.jpg",
   placeholder = debugPlaceholder(R.drawable.debugPlaceholder),
   contentDescription = stringResource(R.string.description)
)

And create an util method:

@Composable
fun debugPlaceholder(@DrawableRes debugPreview: Int) =
    if (LocalInspectionMode.current) {
        painterResource(id = debugPreview)
    } else {
        null
    }

You can see more here: https://coil-kt.github.io/coil/compose/

like image 116
Vince Avatar answered Sep 05 '25 01:09

Vince


Just as an update on cd1 Answer:

rememberCoilPainter is renamed to rememberImagePainter and its arguments changed

More info about the changes:

  • rememberCoilPainter is renamed to rememberImagePainter and its arguments changed:
  • shouldRefetchOnSizeChange is replaced with onExecute, which has more control over if image requests are executed or skipped.
  • requestBuilder is renamed to builder.
  • fadeIn and fadeInDurationMs are removed. Migrate to ImageRequest.Builder.crossfade.
  • previewPlaceholder is removed. ImageRequest.placeholder is now automatically used if inspection mode is enabled.
  • LoadPainter is renamed to ImagePainter.
  • ImagePainter no longer falls back to executing an image request with the root view's size if onDraw is not called. This is most likely to be noticeable if you use ImagePainter in a LazyColumn and the Image's size isn't constrained. Loader and rememberLoadPainter are removed.
  • LocalImageLoader.current is not-null and returns the singleton ImageLoader by default.
  • DrawablePainter and rememberDrawablePainter are now private.

source: https://coil-kt.github.io/coil/compose/

Regarding placeholder visible in preview, the code is:

Image(
    painter = rememberImagePainter(
        data = "https://www.example.com/image.jpg",
        builder = {
            placeholder(R.drawable.placeholder)
        }
    ),
    contentDescription = "some description",
)
like image 21
Kuruchy Avatar answered Sep 04 '25 23:09

Kuruchy