Set ImageView`s size with Glide for each item in RecyclerView, the image size is changing

Viewed 2850

In RecyclerView, I want to load images for each item using their original aspect ratio. The server don't return the size of image.

My code is as follows:

@Override
public void onBindViewHolder(K holder, int position) {
    // ....
    Glide.with(mContext)
         .load(imgUrls.get(position))
         .listener(new RequestListener<String, GlideDrawable>(){
            // ...
            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource){
                int drawableWidth = resource.getIntrinsicWidth();
                int drawableHeight = resource.getIntrinsicHeight();
                double ratio = (drawableWidth * 1.0) / (drawableHeight * 1.0);
                // depend on the ratio to set the imageView`s LayoutParams to change the imageView`s size.
                .........
                layoutParams.width = xx;
                layoutParams.height = xx;
                imageView.setLayoutParams(layoutParams);
                return false;
            }
         })
         .into(imageView);
}

But when I have scrolled the RecyclerView or refreshed the RecyclerView, the value of drawableWidth was changed, so the size of the imageView was changed that is not expected.

What is the right way to set ImageView's size in RecyclerView?

2 Answers

Try this one:

    Glide.with(getContext().getApplicationContext())
                 .asBitmap()
                 .load(path)
                 .into(new SimpleTarget<Bitmap>() {
                     @Override
                     public void onResourceReady(Bitmap bitmap,
                                                 Transition<? super Bitmap> transition) {

                /*
                        requestLayout()
                        Call this when something has changed which has
                        invalidated the layout of this view.
                */
                    mImageView.requestLayout();
                    mImageView.getLayoutParams().height = newHeight;
                    mImageView.getLayoutParams().width = newWidth;


                  // Set the scale type for ImageView image scaling 
                  mImageView.setScaleType(ImageView.ScaleType.FIT_XY);

                         mImageView.setImageBitmap(bitmap);
                     }
                 });

You can set the size of the image views using glide it self.

Glide  
.with(context)
.load(UsageExampleListViewAdapter.eatFoodyImages[0])
.override(600, 200) // resizes the image to these dimensions (in pixel). resize does not respect aspect ratio
.into(imageViewResize);
Related