marginTop does not work with ConstraintLayout and wrap_content

It took me a while to figure out I was thinking about this the wrong way, so maybe it will help someone else.

In a ConstraintLayout, it is making a margin from the constraint.

In other words, let's say you have two buttons next to each other.

The one on the right is constrained StartToEnd, TopToTop, and BottomToBottom to the one on the left.

If you give the right one a marginBottom, it's not going to push things below it down, it's going to push itself up from the bottom of the first button. The margin is between its bottom line and the bottom line of the thing it's constrained to, not between all views on the screen.


try this

<Button
    android:id="@+id/button_welcome_signin"
    style="@style/MyAppSubButton"
    android:layout_width="match_parent"
    android:layout_height="46dp"
    android:layout_marginTop="16dp"
    android:text="@string/welcome_sign_in"
    MyAppApp:layout_constraintBottom_toBottomOf="parent"
    MyAppApp:layout_constraintEnd_toEndOf="parent"
    MyAppApp:layout_constraintStart_toStartOf="parent"
    MyAppApp:layout_constraintTop_toBottomOf="@+id/button_welcome_signup" />

Within a ConstraintLayout, side margins for a child view will only take effect if that side is constrained to another view. In your original example, bottom margin on the top button works because the top button has a bottom constraint:

MyAppApp:layout_constraintBottom_toTopOf="@id/button_welcome_signin"

However, top margin on the bottom button doesn't work because the bottom button has no constraint for its top.

If you would like to use top margin on the bottom button, add this constraint:

MyAppApp:layout_constraintTop_toBottomOf="@+id/button_welcome_signup"

Note that you will also have to update the chain style (since this new constraint creates a chain) by adding this attribute to the top button:

MyAppApp:layout_constraintVertical_chainStyle="packed"