LinearLayout子视图等高适配问题:需匹配最高子项高度且支持点击
解决Android布局子视图等高且父容器由最高子视图决定高度的问题
这个布局需求我之前也碰到过,核心就是要让两个子视图不管内容高度如何,都保持一致高度,同时父容器高度由最高的子视图撑开。先分析下你当前布局的问题:
当前布局中,llTitle的高度设为wrap_content,只有当它的内容比tvValueTop高时,父容器llCustomValueContainer的高度才会被它撑开,tvValueTop因为设置了match_parent会跟着拉伸;但如果tvValueTop的内容更高,父容器高度会被tvValueTop撑开,可llTitle还是保持自身内容的高度,无法拉伸,导致两者高度不一致,点击区域也不完整。
下面给你两种可行的解决方案:
方案一:修改LinearLayout子视图属性(最简单)
只需要把llTitle的android:layout_height从wrap_content改成match_parent,就能实现需求:
<LinearLayout android:id="@+id/llCustomValueContainer" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:id="@+id/llTitle" android:layout_width="0dp" android:layout_height="match_parent" <!-- 关键修改:从wrap_content改为match_parent --> android:layout_weight="1" android:orientation="vertical"> <!-- some content of undefined height --> </LinearLayout> <TextView android:id="@+id/tvValueTop" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center_vertical"/> </LinearLayout>
修改后,不管llTitle还是tvValueTop哪个内容更高,父容器的高度都会被最高的子视图撑开,另一个子视图因为设置了match_parent,会自动拉伸到和父容器相同的高度,完美满足你的三个需求:父容器高度由最高子视图决定、两个子视图等高、点击区域覆盖完整高度。
方案二:使用ConstraintLayout(更灵活,推荐)
如果你的项目已经引入了ConstraintLayout,用它来实现会更灵活,后续调整布局也更方便:
<androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/llCustomValueContainer" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1"> <LinearLayout android:id="@+id/llTitle" android:layout_width="0dp" android:layout_height="match_parent" android:orientation="vertical" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toStartOf="@+id/tvValueTop" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintHorizontal_weight="1"> <!-- some content of undefined height --> </LinearLayout> <TextView android:id="@+id/tvValueTop" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center_vertical" app:layout_constraintStart_toEndOf="@+id/llTitle" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
这里通过将两个子视图的top和bottom都绑定到父容器的top和bottom,同时给llTitle设置水平权重让它占据剩余宽度。父容器高度会自动由内容更高的子视图决定,另一个子视图会被约束拉伸到相同高度,完全符合你的需求。
内容的提问来源于stack exchange,提问作者prom85
相关产品推荐
相关产品推荐

