如何在 ConstraintLayout 中设置负值的 Margin

假如有现在这样一个需求,两个控件:一个 ImageView 和 一个 TextView
位置要求:y 轴方向,TextView 在 ImageView 的底线之上 20dp;x 轴方向,TextView 在 ImageVIew 的右边线的左边 20dp。

如果使用传统的 RelativeLayout,很简单,设置 ImageView 和 TextView 的相对位置之后,设置 TextView 的 android:layout_marginStartandroid:layout_marginTop 为 -20 即可达到上述需求。

  • 在 RelativeLayout 内部的控件,它的 Margin 可以设置为负数,并且是起作用的
  • 在 ConstraintLayout 内部的控件,它的 Margin 可以设置为负数,但是不起作用

如果使用 ConstraintLayout 的,就不能通过设置 TextView 控件的 android:layout_marginStartandroid:layout_marginTop 为 -20 达到上述需求。

我们可以换种思路,在 SDK 内提供了另一个控件 android.widget.Space,其官方说明如下所示:

Space is a lightweight View subclass that may be used to create gaps between components in general purpose layouts.(Space是一个轻量级的View子类,可用于在通用布局中创建组件之间的间隙)

使用 ConstraintLayout 和 Space 实现上图所示的 xml 布局文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:contentDescription="@null"
        android:src="@mipmap/ic_launcher"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.widget.Space
        android:id="@+id/space"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="20dp"
        android:layout_marginEnd="20dp"
        android:background="@android:color/holo_blue_bright"
        app:layout_constraintBottom_toBottomOf="@+id/iv"
        app:layout_constraintEnd_toEndOf="@+id/iv" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:background="@android:color/holo_blue_bright"
        android:gravity="center"
        android:text="Hello World!"
        android:textColor="@android:color/white"
        app:layout_constraintStart_toEndOf="@+id/space"
        app:layout_constraintTop_toBottomOf="@+id/space" />
</android.support.constraint.ConstraintLayout>

注:Space 控件也可使用普通 View 控件代替

参考资料:How to achieve overlap/negative margin on Constraint Layout?

上一篇 Android 8.0 BroadcastReceiver静态注册大部分取消,动态注册,有序广播
下一篇 Glide 4.0梳理
目录
文章列表
1 OpenCart Controller自带方法
OpenCart Controller自带方法
2
解决WebView加载URL跳转到系统浏览器的问题
解决WebView加载URL跳转到系统浏览器的问题
3
Android USB通信入门篇
Android USB通信入门篇
4
面试题:说一下 Spring Boot 自动装配原理?
面试题:说一下 Spring Boot 自动装配原理?
5
PHP编译安装ldap扩展模块
PHP编译安装ldap扩展模块
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。