在RecyclerView中为每个项目设置带有Glide的ImageView大小,图像大小正在变化

问题描述 投票:0回答:2

在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大小的正确方法是什么?

android android-recyclerview android-glide
2个回答
3
投票

试试这个:

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

1
投票

您可以使用自己滑动来设置图像视图的大小。

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);
© www.soinside.com 2019 - 2024. All rights reserved.