如何让已约束至View顶部的Constraint Layout超出对应边界
实现ConstraintLayout保留约束同时超出锚点View顶部的方案
目前有两种常用的实现方式,均可以保留原有约束关系,同时达到超出边界的效果:
- 方案1:使用负margin(最简单,适配绝大多数场景)
你已经将目标ConstraintLayout的底部约束到锚点View的顶部,直接给该ConstraintLayout设置负的底部边距即可,比如要向上超出50dp,就设置android:layout_marginBottom="-50dp"。
需要额外给所有上层的父布局添加关闭裁剪的属性,避免超出的部分被隐藏:
<!-- 父布局层级添加如下两个属性 --> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" android:clipChildren="false" android:clipToPadding="false"> <!-- 锚点View --> <View android:id="@+id/anchor_view" android:layout_width="match_parent" android:layout_height="200dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent"/> <!-- 需要超出顶部的ConstraintLayout --> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/floating_cl" android:layout_width="match_parent" android:layout_height="100dp" android:layout_marginBottom="-50dp" app:layout_constraintBottom_toTopOf="@id/anchor_view" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
如果需要动态调整超出距离,直接修改layout_marginBottom的数值即可,不需要修改原有约束规则。
- 方案2:使用辅助View + 垂直偏移bias(适合动态调整比例的场景)
如果需要按自身高度比例调整超出距离,不需要硬编码具体数值,可以新增一个高度为0的辅助占位View,将辅助View的底部约束到锚点View顶部,再把目标ConstraintLayout的底部约束到辅助View的顶部,设置app:layout_constraintVertical_bias大于1即可,比如设置为1.3就代表向上超出自身高度的30%:
<!-- 辅助占位View --> <View android:id="@+id/guide_view" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintBottom_toTopOf="@id/anchor_view" app:layout_constraintStart_toStartOf="parent"/> <!-- 目标ConstraintLayout --> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/floating_cl" android:layout_width="match_parent" android:layout_height="100dp" app:layout_constraintBottom_toTopOf="@id/guide_view" app:layout_constraintTop_toTopOf="@id/guide_view" app:layout_constraintVertical_bias="1.3" app:layout_constraintStart_toStartOf="parent"/>
注意:两种方案都需要确保所有上层非滚动父容器都设置
clipChildren="false"和clipToPadding="false",否则超出父布局边界的部分会被裁剪,无法正常显示。
内容的提问来源于stack exchange,提问作者Mike087
相关产品推荐
相关产品推荐

