You need to enable JavaScript to run this app. Android开发:RecyclerView条目布局中Glide加载图片时ProgressBar仅显示一半
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:RecyclerView条目布局中Glide加载图片时ProgressBar仅显示一半

问题根因

进度条仅显示一半的核心原因出在iv_hotel的高度设置逻辑:

  • iv_hotel使用wrap_content作为高度,设计预览时因为设置了srcCompat占位图,有固定高度参考,渲染效果正常。
  • 实际运行时Glide异步加载图片,图片加载完成前iv_hotel无实际内容,wrap_content计算得到的高度为0。此时progress_hotel_image上下约束对齐这个高度为0的ImageView,自身中心会落在ImageView的顶部边界位置,上半部分被外层CardView裁切,仅露出下半段。
解决方案

按照以下步骤修改布局,即可解决问题,同时优化布局规范性:

  1. 修正iv_hotel的尺寸约束,保证无论图片是否加载完成,ImageView的尺寸都是确定的:
    • 将不规范的android:layout_width="match_parent"替换为0dp(这是ConstraintLayout中子View占满可用宽度的标准写法)
    • 增加宽高比约束,避免高度在图片加载前变为0,可根据实际业务选择合适的图片比例,比如常用的酒店展示图16:9比例
    • 补充图片缩放属性,避免加载的图片变形
      修改后的ImageView核心代码:
    <ImageView
        android:id="@+id/iv_hotel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        app:layout_constraintDimensionRatio="16:9"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_launcher_background" />
    
  2. 调整ProgressBar的约束逻辑,保证它始终居中在ImageView区域内:
    因为现在ImageView的尺寸是固定的,保留原有对齐逻辑的同时,去掉多余的水平偏移参数,将左右约束对齐到ImageView而非父布局,避免位置偏移:
    <ProgressBar
        android:id="@+id/progress_hotel_image"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="@id/iv_hotel"
        app:layout_constraintEnd_toEndOf="@id/iv_hotel"
        app:layout_constraintStart_toStartOf="@id/iv_hotel"
        app:layout_constraintTop_toTopOf="@id/iv_hotel" />
    
    (原布局中写死的layout_constraintHorizontal_bias="0.498"是预览时手动调整的参数,实际运行会导致进度条偏移,建议删除)
额外优化建议
  • 如果业务需要根据图片实际比例动态调整ImageView高度,可以不用固定宽高比,而是给iv_hotel加上android:adjustViewBounds="true",同时在Glide加载时使用占位图保证ImageView在加载前有最小高度,避免再次出现高度为0的问题。
  • 检查下方tv_suites_available的约束:该View设置了宽度为0dp,但仅约束了左侧位置,未约束右侧到父布局边界,实际运行时宽度仍为wrap_content,可补充app:layout_constraintEnd_toEndOf="parent"让它正确占满剩余宽度。

内容的提问来源于stack exchange,提问作者Дмитрий

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.04 23:57:01