How to make ConstraintLayout work with percentage values?
It may be useful to have a quick reference here.
Placement of views
Use a guideline with app:layout_constraintGuide_percent
like this:
<androidx.constraintlayout.widget.Guideline android:id="@+id/guideline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintGuide_percent="0.5"/>
And then you can use this guideline as anchor points for other views.
or
Use bias with app:layout_constraintHorizontal_bias
and/or app:layout_constraintVertical_bias
to modify view location when the available space allows
<Button ... app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintHorizontal_bias="0.25" ... />
Size of views
Another percent based value is height and/or width of elements, with app:layout_constraintHeight_percent
and/or app:layout_constraintWidth_percent
:
<Button ... android:layout_width="0dp" app:layout_constraintWidth_percent="0.5" ... />
You can currently do this in a couple of ways.
One is to create guidelines (right-click the design area, then click add vertical/horizontal guideline). You can then click the guideline's "header" to change the positioning to be percentage based. Finally, you can constrain views to guidelines.
Another way is to position a view using bias (percentage) and to then anchor other views to that view.
That said, we have been thinking about how to offer percentage based dimensions. I can't make any promise but it's something we would like to add.
As of "ConstraintLayout1.1.0-beta1" you can use percent to define widths & heights.
android:layout_width="0dp"app:layout_constraintWidth_default="percent"app:layout_constraintWidth_percent=".4"
This will define the width to be 40% of the width of the screen.A combination of this and guidelines in percent allows you to create any percent-based layout you want.