Home > Back-end >  Downloading an image using Glide and returning the drawable
Downloading an image using Glide and returning the drawable

Time:07-15

I am currently using Glide to download an image using a URL and using that to load the image in the imageView. This is how I am doing it:

Glide.with(cardView)
        .load(urls.get(0))
        .centerCrop()
        .into(imageView1);

Now, I want that I seperate out the process of downloading the image using Glide and setting the image in the imageView.

I want to do it such that I create a function which downloads the image using Glide and returns a drawable/bitmap. And then after it is done downloading, I pass it to setting the image in the imageView.

The reason I am doing it is because I Want to make a generic function in parent class that takes in a URL and downloads the image, and then this function can be used by different child classes as per their own need.

CodePudding user response:

For asynchronous calls, you can do something like this:

Glide.with(this)
        .asBitmap()
        .load(imageUrl)
        .into(object : CustomTarget<Bitmap>(){
            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                // Here resource is the bitmap object
            }
            override fun onl oadCleared(placeholder: Drawable?) {
            }
        })

For synchronous calls, you can use this method:

val bitmap = Glide.with(this).asBitmap().load(imageUrl).submit().get();

You might wanna use the synchronous method because you want to return the bitmap :)

CodePudding user response:

First of all download your image by one of netowkring library(recomended okhttp, retrofit or volley). After that set your downloaded image as bitmap or as drawable by converting it to imageView.

  • Related