25

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.

chancyWu
  • 14,073
  • 11
  • 62
  • 81
Softlion
  • 12,281
  • 11
  • 58
  • 88
  • You can try to constrain items to either left or right of that guide. This will position that item nearly relative to layout guide. – Lalit Fauzdar Aug 14 '17 at 09:10

5 Answers5

57
android:translationX="-10dp"
android:translationY="-10dp"
Pnemonic
  • 1,685
  • 17
  • 17
26

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.

Cheticamp
  • 61,413
  • 10
  • 78
  • 131
10

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!

user14678216
  • 2,886
  • 2
  • 16
  • 37
1

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" />
Hadi Note
  • 1,386
  • 17
  • 16
0

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