The ConstraintSetBuilder allows you to define relationships between views within a ConstraintLayout. You can target views by their ID or by the View object itself.
Connecting Views
Connections are created using the of and to infix functions. You can define a basic connection or a connection with a margin.
- Basic Connection:
Side.LEFT of viewId to Side.RIGHT of targetId - Margin Connection:
(Side.LEFT of viewId to Side.RIGHT of targetId).margin(16)
View Properties
Inside a view's configuration block, you can set various properties:
- Dimensions:
width, height, maxWidth, maxHeight, minWidth, minHeight, defaultWidth, defaultHeight. - Bias & Weight:
horizontalBias, verticalBias, horizontalWeight, verticalWeight. - Transformations:
alpha, rotationX, rotationY, scaleX, scaleY, translationX, translationY, translationZ, transformPivotX, transformPivotY. - Other:
visibility, dimensionRatio, applyElevation, elevation.
Clearing Constraints
Use clear() to remove all constraints from a view, or clear(sideId) to remove a constraint from a specific side.
Match Constraint
Use the matchConstraint property to set a dimension to MATCH_CONSTRAINT (equivalent to 0 in ConstraintLayout params).
constraintLayout.applyConstraintSet {
val view1Id = R.id.view1
val view2Id = R.id.view2
view1Id {
width = ConstraintLayout.matchConstraint
height = 100
// Connect view1's left to parent's start
(Side.START of this@ConstraintSetBuilder) to (Side.START of view1Id).margin(16)
}
view2Id {
// Connect view2's top to view1's bottom
(Side.TOP of this@ConstraintSetBuilder) to (Side.BOTTOM of view1Id)
}
}