Ask Your Question
2

How to display a progress bar while an image loads with Coil?

asked 2023-06-16 21:50:49 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-16 22:10:01 +0000

woof gravatar image

You can achieve this by using the RequestBuilder class in Coil. First, create a RequestBuilder and set the URL of the image you want to load. Then, create a ProgressBar and set its visibility to VISIBLE to show it on the screen while the image is loading. Finally, set a listener on the RequestBuilder to hide the ProgressBar when the image is loaded. Here's an example code:

val imageRequest = ImageRequest.Builder(context)
    .data(imageUrl)
    .build()

val requestBuilder = Coil.imageLoader(context).enqueue(imageRequest) {
    target(onSuccess = { result ->
        // The image has loaded successfully, hide the progress bar
        progressBar.visibility = View.GONE
        imageView.setImageDrawable(result)
    }, onError = { error ->
        // Handle the error
    })
}

// Show the progress bar while the image is loading
requestBuilder.addLifecycleListener(
    object : LifecycleObserver {
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onStart() {
            progressBar.visibility = View.VISIBLE
        }
    }
)

Note that in this example, imageView is the ImageView where you want to display the loaded image, and progressBar is the ProgressBar to show while the image is loading. Also, make sure to add the Coil dependency to your project.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-16 21:50:49 +0000

Seen: 14 times

Last updated: Jun 16 '23