android ConstraintLayout 不允许负边距

android ConstraintLayout does not allow negative margins

我根据布局指南定位了很多项目, 并希望将新项目放置在与此布局指南几乎相关的位置。

我尝试使用负版面边距但没有成功。

此答案现已过时。请参阅已接受的答案以获取更新。



这里有一篇 blog posting 讨论了 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"

您可以使用视图来保存固定值,例如 30dp,如下所示:

 <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" />

为兄弟姐妹的位置创建视图可能不是最好的选择,因为视图将被绘制(即使它是不可见的)它仍然会使用资源。

您可以尝试使用指南:

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

2020 年 12 月 17 日,ConstraintLayout 2.1.0 alpha 2 中添加了对 ConstraintLayout 中设置负边距的支持。

您可以通过将依赖项设置为来更新它:

implementation 'androidx.constraintlayout:constraintlayout:2.1.0-alpha2'

完整的变更日志可在此处获得:https://androidstudio.googleblog.com/2020/12/constraintlayout-210-alpha-2.html 其中包括:

ConstraintLayout

  • supports negative margins for constraints

这意味着现在您可以做 android:layout_marginTop="-25dp" 等您以前做不到的事情!