glide为列表加载大小不固定的图片

目标:

        有一个列表,每个item中都有一个 ImageView,要求 ImageView 尺寸等于图片内容尺寸;当图片最大宽度超过屏幕宽度时,ImageView 宽度就固定为屏幕宽度,保持原图宽高比缩放显示图片。

实现如下代码:

RequestOptions mOptions = new RequestOptions()
                //.placeholder(R.mipmap.icon_image_place_holder)
                .error(R.mipmap.icon_image_place_holder)
                .override(mMaxWidth, 3000)
                .priority(Priority.NORMAL);

Glide
                .with(mContext)
                .load(url)
                .apply(mOptions)
                .listener(new RequestListener() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource){
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
                        if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY) {
                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        }

                        ViewGroup.LayoutParams params = imageView.getLayoutParams();

                        params.width = Math.min(mMaxWidth, resource.getIntrinsicWidth());
                        params.height = (resource.getIntrinsicHeight() * params.width) / resource.getIntrinsicWidth();
                        imageView.setLayoutParams(params);

                        return false;
                    }
                })
                .into(imageView);

遇到的问题:一开始用的options和加载方法如下,发生第一张图片大小与原图一致,后面加载出来的图片很小,与原图不一致

原因:在动态设置图片大小时,imageView.getLayoutParams() 受到了placeholder图片大小的影响(placeholder图片很小,导致maxwidth远远小于真实大图的宽度)

 

mOptions = new RequestOptions()

    .placeholder(R.mipmap.icon_image_place_holder)

    .error(R.mipmap.icon_image_place_holder)

    .priority(Priority.NORMAL);

int maxWidth = imageView.getMaxWidth();
params.width = Math.min(maxWidth, resource.getIntrinsicWidth());
params.height = (resource.getIntrinsicHeight() * params.width) / resource.getIntrinsicWidth();
imageView.setLayoutParams(params);

 

        

你可能感兴趣的:(笔记,android)