How to use image placeholders for preview with Jetpack Compose

Issue

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.

Solution

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",
)

Answered By – Kuruchy

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published