Android 嵌套LinearLayout设wrap_content时内部Button不显示如何修复
问题核心原因
你当前出现显示异常是两个错误叠加导致的:
- 使用
layout_weight分配水平方向宽度时,两个Button的android:layout_width都错误设置为fill_parent,正确写法应该是设为0dp,否则会触发测量逻辑混乱 - 第一行水平LinearLayout设置为
wrap_content时,右侧刷新Button的layout_height设为match_parent,但此时父容器还没计算出高度,会先将右侧Button高度测量为0,导致整行高度计算错误,左侧Button显示错位
修复方案
方案1:保留原有LinearLayout结构快速修复
把第一行水平LinearLayout的代码修改为如下即可:
<LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:weightSum="9"> <Button android:id="@+id/ex1" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="#AFEEEE" android:fontFamily="sans-serif" android:onClick="ShowExercise" android:text="Exercise" android:textColor="#FFFFFF" android:textSize="24sp"/> <Button android:id="@+id/ex1_refresh_button" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="8" android:background="@drawable/icon_refresh" android:onClick="refresh" android:minHeight="0dp"/> </LinearLayout>
如果要让右侧Button宽度等于自身高度,此方案无法完美适配,推荐使用方案2。
方案2:替换行容器为ConstraintLayout(更推荐,完全匹配需求)
直接将所有行的水平LinearLayout替换为如下写法,不需要设置任何固定高度,自动满足:左侧Button高度由内容决定,右侧图标Button宽度等于自身高度的要求:
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- 左侧Exercise按钮 --> <Button android:id="@+id/ex1" android:layout_width="0dp" android:layout_height="wrap_content" android:background="#AFEEEE" android:fontFamily="sans-serif" android:onClick="ShowExercise" android:text="Exercise" android:textColor="#FFFFFF" android:textSize="24sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toStartOf="@id/ex1_refresh_button" /> <!-- 右侧刷新按钮 --> <Button android:id="@+id/ex1_refresh_button" android:layout_width="0dp" android:layout_height="0dp" android:background="@drawable/icon_refresh" android:onClick="refresh" app:layout_constraintDimensionRatio="1:1" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
逻辑说明:
- 左侧Button上下贴齐父容器,高度由自身文本内容决定,自动撑满整行高度
- 右侧Button同样上下贴齐父容器,高度和左侧Button保持一致,
app:layout_constraintDimensionRatio="1:1"属性强制宽度等于高度,完美符合要求 - 适配性更强,左侧Button文本内容变化时整行高度自动适配,不需要手动修改固定高度值
内容的提问来源于stack exchange,提问作者Inbaral
相关产品推荐
相关产品推荐

