I am trying to use the Coil image loading library in an Android View project with mixed Java-Kotlin source code.
https://github.com/coil-kt/coil
I am following this guide about how to use the library in Java:
https://coil-kt.github.io/coil/java_compatibility/
I have added the library to my gradle app file:
implementation("io.coil-kt.coil3:coil:3.2.0")
implementation("io.coil-kt.coil3:coil-network-okhttp:3.2.0")
However, the compiler raises an incompatible types error in the following Java code.
ImageRequest request = new ImageRequest.Builder(context)
.data("https://example.com/image.jpg")
.crossfade(true)
.target(imageView)
.build();
imageLoader.enqueue(request);
error: incompatible types: ImageView cannot be converted to Target .target(imageView)
and in the following one the compiler is not able to find any ImageLoaders at all
ImageRequest request = new ImageRequest.Builder(context)
.data("https://example.com/image.jpg")
.size(1080, 1920)
.build();
Drawable drawable = ImageLoaders.executeBlocking(imageLoader, request).getImage().asDrawable(context.resources);
Am I missing anything? How can I use this library in Java?
After reading documentation, I think Coil 3.x no longer accepts a raw ImageView
in .target()
. Instead, you must wrap the ImageView
in a Target
.
Use ViewTarget
(Coil's wrapper) in Java like this:
import coil.target.ViewTarget;
ImageRequest request = new ImageRequest.Builder(context) .data("https://example.com/image.jpg")
.crossfade(true)
.target(new ImageViewTarget(imageView))
.build();
imageLoader.enqueue(request);
ImageLoaders.executeBlocking()
method in Coil 3.x. Coil 3 moved to suspending functions, and Java cannot directly call suspend functions like execute
.To use execute
in Java, you must bridge through Kotlin. Here's how you can do it:
// Kotlin
import android.content.Context
import coil.ImageLoader
import coil.request.ImageRequest
import coil.request.SuccessResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import android.graphics.drawable.Drawable
fun loadImageBlocking(context: Context, imageLoader: ImageLoader, request: ImageRequest): Drawable? {
return runBlocking {
val result = imageLoader.execute(request)
if (result is SuccessResult) {
return@runBlocking result.drawable
}
return@runBlocking null
}
}