Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate Glide with onBindViewHolder?

Tags:

android

I have an adapter that displays user name and a user image. My User class has a getter method to get the user id, and the user image uri (from Firebase). But how to set the image to image view? Right now I set the user name simply by using setText:

      @Override
      public void onBindViewHolder(MyViewHolder holder, int position) {
          myHolder = holder;
          User user = mDataset.get(position);  
          myHolder.userNameTextView.setText(user.getUsername()); 
//how to integrate Glide here? assuming I have a getter method which returns the user image uri as String?

This Glide implementation works for me(on a separate activity, not on the adapter):

       Glide.with(this /* context */)
                .load(uri)
                .into(test);

Now assume I have a getter method in the User class which returns the image Uri, how to integrate it in the OnBindViewHolder? I can't make it work together

like image 411
LesserFlow Avatar asked Dec 17 '18 23:12

LesserFlow


1 Answers

You don't have to do anything special to use Glide with RecyclerView. The only concern is getting ahold of a Context object to pass to the Glide.with() call, but every ViewHolder has a field called itemView and every View has a getContext() method, so you can use those.

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    User user = mDataset.get(position);  
    holder.userNameTextView.setText(user.getUsername());

    String uri = user.getAvatarUri(); // or whatever you want
    Glide.with(holder.itemView.getContext()).load(uri).into(holder.imageView);
}
like image 158
Ben P. Avatar answered Sep 29 '22 03:09

Ben P.