贝利信息

RecyclerView图片加载失败?可能是这几个原因

日期:2024-11-30 00:00 / 作者:心靈之曲

recyclerview 渲染服务端图片不显示的原因

使用 recyclerview 显示服务端图片时,如果图片不显示,可能是因为以下原因:

在布局文件中,如果 imageview 的高度设置为 wrap_content,则在图片加载之前,系统无法确定其高度,从而导致无法显示。

解决方案:

动态设置 imageview 高度

如果需要动态设置 imageview 高度,可以使用 glide 的监听器:

Glide.with(this.activity.getBaseContext())
    .load(src)
    .addListener(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) {
            // 根据图片宽高比设置 ImageView 高度
            int width = imageView.getWidth();
            float aspectRatio = (float) resource.getIntrinsicWidth() / (float) resource.getIntrinsicHeight();
            int height = Math.round(width / aspectRatio);
            image

View.setLayoutParams(new ViewGroup.LayoutParams(width, height)); return false; } }) .into(imageView);