Load image from url in viewholder

Viewed 384

I'm trying to load an image to my viewholder from a URL but I'm not sure how to do that. I tried with setImageUri and Picasso but since I have the parameter from the bind function, I am not sure where to pass it since I want to pass the url instead and that does not seem to work that way. What's the right way to do this?

This is the code:

class ViewHolder (private val binding: ItemDetailBinding
): RecyclerView.ViewHolder(binding.root) {
   fun bind(item:String){
       Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(binding.ivItem)
   }
}

2 Answers

You can do it in onBindViewHolder in your recycler view adapter:

override fun onBindViewHolder(holder: MyViewHolder,position: Int) {
    Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(holder.yourImageView)
}

You can still pass the url from the parameter passed from the bind() function. And one more thing, you should replace Picasso to Glide. There is a lot of information on why to use Glide instead of Picasso.

For example, I have a data class called User as follows:

data class User (
    val name: String? = null,
    val avatarUri: String? = null
)

Then create a view holder for your User. In the view holder you have an image view, that image view will load the image from Picasso.

class MyViewHolder (
    private val binding: ItemDetailBinding
) : RecyclerView.ViewHolder(binding.root) {

    fun bind(item: User) {
        binding.executePendingBindings()
        Picasso.get().load(item.avatarUri).into(binding.ivItem)
    }
}

Finally in the ListAdapter, specifically the function onBindViewHolder(), you call the bind function of the view holder and pass the parameter into it.

class MoviesAdapter : ListAdapter<User, MyViewHolder>(MyDiffUtil) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val inflate = ItemDetailBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return MyViewHolder(inflate)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.bind(getItem(position))
    }
}

object MyDiffUtil : DiffUtil.ItemCallback<User>() {

    override fun areItemsTheSame(oldItem: User, newItem: User): Boolean =
        oldItem.name == newItem.name
    
    override fun areContentsTheSame(oldItem: User, newItem: User): Boolean =
        oldItem == newItem
}
Related