android ConstraintLayout does not allow negative margins

断了今生、忘了曾经 提交于 2019-12-05 01:37:31

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.

android:translationX="-10dp"
android:translationY="-10dp"

It's a Bad practice to use NEGATIVE MARGIN .

A ConstraintLayout is a ViewGroup which allows you to position and size widgets in a flexible way.

Note that a margin can only be positive or equals to zero .ConstraintLayout cannot have negative margins.

You can use

  • android:layout_marginStart
  • android:layout_marginEnd
  • android:layout_marginLeft
  • android:layout_marginTop
  • android:layout_marginRight
  • android:layout_marginBottom

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!