Search code examples
androidimageviewdrawableandroid-drawablecoil

Coil ImageRequest for drawable resource


I'm trying to prepare Coil's ImageRequest as:

val drawable = when {
        mimeType.startsWith("image") -> R.drawable.ic_baseline_image_24
        mimeType.startsWith("video") -> R.drawable.ic_baseline_ondemand_video_24
        mimeType.startsWith("audio") -> R.drawable.ic_baseline_audiotrack_24
        else -> R.drawable.ic_baseline_attach_file_24
}
val imageRequest = ImageRequest.Builder(context)
        .data(drawable)
        .crossfade(true)
        .target(imageView)
        .build()

//blah-blah
// and somewhere deep inside code
imageLoader.enqueue(imageRequest)

But it doesn't work.

I suppose there should be another approach, or does ImageRequest not support local drawable?


Solution

  • Based on the Coil Documentation

    All requests should set data (i.e. url, uri, file, drawable resource, etc.). This is what the ImageLoader will use to decide where to fetch the image data from. If you do not set data, it will default to NullRequestData.

    And It's seems like you're doing it correctly. I verified it on my end, you could checkout this Github Repository. Where I tried to recreate the issue you've mentioned and it's working perfectly. Please review your imageView's height width or the constraints (if you're using constraint layout) layout.