Friday, December 28, 2018

Centering Widgets with ConstraintLayout in Android

Placing widgets in the exact place you want on an Android layout is a difficult task. With ConstraintLayout, you can achieve this relatively easy. In a ConstraintLayout, you can use below configuration to center the button in the window.

<Button
        android:id="@+id/testbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Test"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Interestingly this will add the button in the center of the window like below.

If we consider horizontal positioning, we have configured to place the left of the button to the left of the parent, (which refers to the parent container, i.e. the ConstraintLayout) and place the right of the button to the right of the parent. This is an impossible layout unless the width of the button is equal to the width of the parent. ConstraintLayout handles this by placing the button in the center of the parent, like pulling the button by the two constraints resulting to make the button keep in the middle. Same goes with the vertical positioning.






But if you add a bias to position the widget in favor of one side. For example, if we add below bias to the above positioning, the result will be as below image.

<Button
        ...
        app:layout_constraintVertical_bias="0.8" />

If we add the bias as 0.8, the widget will be placed after 80% of the container.

No comments:

Post a Comment