I position lots of items relative to a layout guide, and would like to position a new item nearly relative to this layout guide.
I tried with a negative layout margin without success.
I position lots of items relative to a layout guide, and would like to position a new item nearly relative to this layout guide.
I tried with a negative layout margin without success.
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.
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!
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" />
Creating a view for position your siblings might not be the best call because the view will be drawn (even if it's invisible) it will still uses ressources.
You can try to use guidelines instead :
You can add a vertical or horizontal guideline to which you can constrain views, and the guideline will be invisible to app users. You can position the guideline within the layout based on either dp units or percent, relative to the layout's edge.
https://developer.android.com/training/constraint-layout#constrain-to-a-guideline