android ConstraintLayout does not allow negative margins
Support for setting negative margin in a ConstraintLayout
has been added in ConstraintLayout 2.1.0 alpha 2 on the 17th of December 2020.
You can update to it by setting the dependency to:
implementation 'androidx.constraintlayout:constraintlayout:2.1.0-alpha2'
The full changelog is available here: https://androidstudio.googleblog.com/2020/12/constraintlayout-210-alpha-2.html which includes:
ConstraintLayout
- supports negative margins for constraints
This means that now you can do things such as android:layout_marginTop="-25dp"
, which you couldn't do before!
android:translationX="-10dp"
android:translationY="-10dp"
This answer is now obsolete. See the accepted answer for an update.
Here is a blog posting that discusses negative margins in ConstraintLayout
.
Using Spaces for negative margins
A view in a ConstraintLayout cannot have negative margins (it’s not supported). However, with an easy trick you can have similar functionality by inserting a Space (which is essentially an empty View) and setting its size to the margin you want.
You can use a View to hold a fixed value like 30dp like below:
<com.mapbox.mapboxsdk.maps.MapView
android:id="@+id/mapView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="45dp"
app:layout_constraintBottom_toBottomOf="@id/space"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:mapbox_uiRotateGestures="false" />
<View
android:id="@+id/space"
android:layout_width="match_parent"
android:layout_height="30dp"
app:layout_constraintTop_toBottomOf="parent" />