AdamK AdamK - 2 months ago 35
Android Question

Evenly spacing views using ConstraintLayout

A common use for

is to evenly space (weight) views, for example:
example layout

How do you implement evenly spaced views like this using the new
ConstraintLayout
?

ConstraintLayout
links for reference: blog post, I/O session video

Answer

To do this using ConstraintLayout you can use a guideline. Right-click anywhere on your layout in the new layout editor:

layout editor right-click menu

Then select "Add Vertical Guideline". A new guideline will appear, that by default, will likely be anchored to the left in relative values (denoted by left-facing arrow):

layout editor relative guideline

Click the left-facing arrow to switch it to a percentage value, then drag the guideline to the 50% mark:

layout editor percent guideline

The guideline can now be used as an anchor for other views. In my example, I attached the right of the save button and the left of the share button to the guideline:

final layout

If you want the views to fill up the available space then the constraint should be set to "Any Size" (the squiggly lines running horizontally):

any size constraint

A guideline can also be created in XML quite easily rather than using the layout editor:

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline"
    android:orientation="vertical"
    app:relativePercent="50" />
Comments