通过代码设置Constraint Layout宽高百分比后布局未调整如何解决
问题原因
- ConstraintSet未克隆原有约束:直接创建空ConstraintSet实例会丢失XML中定义的所有对齐规则、margin属性,百分比规则依赖完整的边界约束才能正常计算,约束缺失自然无法生效。
- applyTo目标对象错误:
constrainPercentHeight/constrainPercentWidth是给父布局下的子控件设置约束规则,规则需要应用到子控件的父ConstraintLayout上,如果代码中applyTo传入的是topView本身,会直接失效。 - 边界约束不全:使用宽度百分比需要子控件左右两侧都设置锚点约束,使用高度百分比需要子控件上下两侧都设置锚点约束,你当前的XML仅配置了顶部和左侧约束,缺少右侧、底部的锚点,百分比没有计算基准。
修复步骤
- 首先修改XML布局,补全
topView的边界约束(如果不需要相对于父布局计算百分比,可将end、bottom的锚点替换为你需要的参考控件):
<androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/topView" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginStart="20dp" android:layout_marginTop="30dp" app:layout_constraintStart_toStartOf="parent" <!-- 补全右侧约束,作为宽度百分比的计算基准 --> app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@id/toolbar" <!-- 补全底部约束,作为高度百分比的计算基准 --> app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintWidth_percent=".35" app:layout_constraintHeight_percent=".30"> </androidx.constraintlayout.widget.ConstraintLayout>
- 修改动态设置约束的Kotlin代码,假设
topView的父ConstraintLayout实例名为parentConstraintLayout:
val set = ConstraintSet() // 克隆父布局原有约束,避免丢失已配置的对齐、margin属性 set.clone(parentConstraintLayout) // 给子控件topView设置宽高百分比 set.constrainPercentHeight(R.id.topView, 0.7F) set.constrainPercentWidth(R.id.topView, 0.3F) // 将规则应用到topView的父布局,而非topView本身 set.applyTo(parentConstraintLayout)
内容的提问来源于stack exchange,提问作者olivia.dayaram
相关产品推荐
相关产品推荐

