javaandroidkotlincoil

How to define the placeholder image for the ImageLoader in Coil v 3.2.0 using Java


I am using Coil in an Android View project with mixed java-kotlin source code.

https://github.com/coil-kt/coil

I am updating the Coil library from v 2.7.0 to v 3.2.0

Old java code for loading an image in a specific ImageView for v 2.7.0

ImageLoader imageLoader = Coil.imageLoader(ContextProvider.getInstance().getActivityContext());
    ImageRequest request = new ImageRequest.Builder(ContextProvider.getInstance().getActivityContext())
            .data(imageUrl)
            .placeholder(R.mipmap.placeholder)
            .size(IMAGE_SIZE, IMAGE_SIZE)
            .target(imageView)
            .build();
imageLoader.enqueue(request);

New java code for loading an image in a specific ImageView for v 3.2.0

    ImageLoader imageLoader = SingletonImageLoader.get(ContextProvider.getInstance().getActivityContext());
    ImageRequest request = new ImageRequest.Builder(ContextProvider.getInstance().getActivityContext())
            .data(imageUrl)
            .placeholder(???)
            .size(IMAGE_SIZE, IMAGE_SIZE)
            .target(new ImageViewTarget(imageView))
            .build();
    imageLoader.enqueue(request); 

I cannot find a clear example of how to set the placeholder image in the new version of the library, and the migration guide is not helpful in this case.

https://coil-kt.github.io/coil/upgrading_to_coil3/

The placeholder method in the new version of the library no longer accepts the resource ID.

old one: .placeholder(R.mipmap.placeholder)

new one: .placeholder(???)

How can I define the placeholder?


Solution

  • You must manually retrieve the Drawable from the resource ID before passing it to placeholder(...) through coil3.DrawableImage

    Context context = ContextProvider.getInstance().getActivityContext();
    Drawable placeholderDrawable = ResourcesCompat.getDrawable(context, R.mipmap.placeholder, null);
    if (placeholderDrawable != null) {
        ImageLoader imageLoader = SingletonImageLoader.get(context);
        DrawableImage placeholderDrawableImage = new DrawableImage(placeholderDrawable, true);
        ImageRequest request = new ImageRequest.Builder(context)
                        .data(imageUrl)
                        .placeholder(placeholderDrawableImage)
                        .size(IMAGE_SIZE, IMAGE_SIZE)
                        .target(new ImageViewTarget(imageView))
                        .build();
        imageLoader.enqueue(request);
    }