recyclerview 渲染服务端图片列表不显示的原因
当使用 recyclerview 渲染服务端图片列表时,如果设置 imageview 的高度为 wrap_content,可能会出现图片不显示的问题。这是因为在加载图片时,系统无法确定图片的大小,从而无法精确测量出 imageview 的高度。
解决方案
解决此问题有几种方法:
- 固定高度: 为 imageview 设置一个固定高度,例如 android:layout_height="200dp"。
- 占位符: 在图片加载期间使用占位符来填充 imageview,例如:
glide.with(context)
.load(imageurl)
.placeholder(r.drawable.placeholder)
.into(imageview)- 动态设置高度: 通过监听器动态设置 imageview 的高度:
Glide.with(context)
.load(imageUrl)
.addListener(object : RequestListener {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target?, isFirstResource: Bo
olean): Boolean {
return false
}
override fun onResourceReady(resource: Drawable?, model: Any?, target: Target?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
// 根据图片宽高比设置 ImageView 的高度
val width = imageView.width
val aspectRatio = resource!!.intrinsicWidth.toFloat() / resource.intrinsicHeight.toFloat()
val height = Math.round(width / aspectRatio)
imageView.layoutParams = ViewGroup.LayoutParams(width, height)
return false
}
})
.into(imageView)









