ConstraintLayout布局异常:元素重叠及Barrier使用问题求助
咱们先逐个解决你的两个疑问:
问题1:为什么初始布局里,明明设了ListView底部约束到按钮顶部,还是会重叠?
核心问题出在ListView的android:layout_height="wrap_content"上。在ConstraintLayout里,wrap_content的逻辑是优先根据View自身的内容计算高度,而你加的layout_constraintBottom_toTopOf只是辅助定位的规则,不会强制限制ListView的最大高度。如果ListView里的内容足够长,它会直接向下延伸,完全无视底部的约束,自然就会和下方的按钮重叠了。
最简单的修复方式:把ListView的layout_height改成0dp(也就是match_constraint)。这样ConstraintLayout就会完全按照上下约束来计算ListView的高度——顶部贴紧父布局顶部,底部贴紧按钮顶部,自动填充中间的可用空间,绝对不会超出边界:
<ListView android:id="@+id/main_list" android:layout_width="match_parent" android:layout_height="0dp" <!-- 关键修改 --> app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toTopOf="@id/rescan" />
问题2:为什么Barrier设了barrierDirection="top"且关联按钮,却跑到按钮下方?
这里有两个你可能没搞清楚的点:
- Barrier的
barrierDirection不是指它的摆放方向:app:barrierDirection="top"的意思是,Barrier会对齐所有引用View的顶部边缘(而不是你以为的“放在View的上方”)。你的按钮是贴紧父布局底部的,所以它的顶部边缘是父布局底部减去按钮自身高度的位置,Barrier会精准对齐这个位置。 - ListView的高度还是没被限制:你最后那个布局里的ListView依然用了
wrap_content,哪怕Barrier位置正确,只要ListView内容过长,它还是会向下延伸覆盖按钮,看起来就像Barrier跑到了屏幕底部。
其实你根本不需要用Barrier来解决这个问题,用第一个问题的修复方案就足够了。如果一定要尝试Barrier,正确的写法应该是这样(重点还是把ListView改成0dp):
<ListView android:id="@+id/main_list" android:layout_width="match_parent" android:layout_height="0dp" <!-- 必须改这里 --> app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toTopOf="@id/bottomBarrier" /> <android.support.constraint.Barrier android:id="@+id/bottomBarrier" android:layout_width="wrap_content" android:layout_height="wrap_content" app:barrierDirection="top" app:constraint_referenced_ids="@id/rescan" /> <android.support.v7.widget.AppCompatButton android:id="@+id/rescan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/rescan_button" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:layout_margin="10dp" /> <!-- 加个margin让按钮和底部有间隔更美观 -->
这样设置后,Barrier会对齐按钮的顶部边缘,ListView的高度被严格限制在父布局顶部到Barrier之间,再也不会和按钮重叠了。
内容的提问来源于stack exchange,提问作者wholerabbit
相关产品推荐
相关产品推荐

