Search code examples
androidandroid-layoutandroid-constraintlayout

ConstraintLayout - Match another view's constraints but add margin to make it larger


I have a TextView, whose width and height is resolved at runtime depending on the text body provided to it. Then I have another View, that needs to exactly match the TextView's top/bottom/start/end constraints, but 16dp larger. Here's what I tried:

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    android:text="Test title"
    />

<View
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintTop_toTopOf="@id/title"
    app:layout_constraintBottom_toBottomOf="@id/title"
    app:layout_constraintStart_toStartOf="@id/title"
    app:layout_constraintEnd_toEndOf="@id/title"
    android:layout_margin="16dp"
    />

The 16dp layout_margin makes the View 16dp smaller than the TextView in all 4 directions, whereas I want to make it 16dp larger. The only solution I've found so far is to declare 4 Spaces (each one 16dp away from one of the constraints), then constrain the View to those Spaces, which honestly seems overkill for what should be a simple layout rule. Do constraint layouts provide an easier way of achieving this?


Solution

  • For the View, set the margins at -16dp as follows:

    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="-16dp"
        android:layout_marginTop="-16dp"
        android:layout_marginEnd="-16dp"
        android:layout_marginBottom="-16dp"
        app:layout_constraintBottom_toBottomOf="@id/title"
        app:layout_constraintEnd_toEndOf="@id/title"
        app:layout_constraintStart_toStartOf="@id/title"
        app:layout_constraintTop_toTopOf="@id/title" />
    

    Do not set android:layout_margin="-16dp". It will not work.

    I am using ConstraintLayout version 2.1.0. Negative margins are not permitted with earlier versions.

    In this image, I have rearranged the views and set background colors to highlight the extent of the views.

    enter image description here