Android ContraintLayout Negative Margin (Partially Outside of Parent View)

This example will put a box at the bottom of the parent view, where 50% of box is outside of / covered by the parent.

  • layout_margin treat negative value as 0
  • To simulate negative margin, create a invisible view. Since I want the box to be at the bottom of parent, I apply bottom contraint to the bottom of parent. Since I want 50% of the box to be visible (another 50% clipped by the parent view), I apply bottom margin using half the height of the box view.
  • To box will apply top constraint to the bottom of the invisible view (putting it below the invisible view).
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                                   xmlns:app="http://schemas.android.com/apk/res-auto"
                                                   xmlns:tools="http://schemas.android.com/tools"
                                                   android:layout_width="match_parent"
                                                   android:layout_height="match_parent">

    <View
        android:id="@+id/hiddenBottomView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="25dp"
        android:background="@color/colorPrimary"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        />

    <ImageView
        android:id="@+id/boxImageView"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="#FE2EF7"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/hiddenBottomView"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.