使用Glide为RecyclerView中的每个项设置ImageView的大小,图片大小在变化。

3
在RecyclerView中,我希望为每个项目加载其原始纵横比的图像。服务器不会返回图像的大小。
我的代码如下:
@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);
}

但是当我滚动 RecyclerView 或者刷新 RecyclerView 后,drawableWidth 的值会改变,导致 imageView 的大小改变,这并不是预期的结果。
在 RecyclerView 中设置 ImageView 大小的正确方式是什么?

为了获得原始的纵横比,您应该在图像视图中使用wrap content,并使用Glide,无需指定大小。 - Jins Lukose
2个回答

2
试试这个:
    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);
                     }
                 });

你的代码中没有使用 w 和 h。 - Vivek Mishra
非常感谢,这样刷新后imageView的大小不会改变,我还在尝试。 - zeqi liu

0

你可以使用Glide本身来设置图像视图的大小。

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);

谢谢,但这不符合要求。 - zeqi liu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接