Search code examples
androidandroid-constraintlayout

How to constraint a view min width equal to height in ConstraintLayout?


I have a TextView need to set the min width equal to the height, that means the view is square when the width <= height, and rectangle when the width > height.

now I hardcode the min width via app:layout_constraintWidth_min="20dp" but seems not work well for all phones.

<androidx.appcompat.widget.AppCompatTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintWidth_min="20dp"
    android:gravity="center_horizontal"/>

It's there has a better solution to constraint it and no need hardcode?

Inspired by @Mike087 the following code finally worked

<androidx.appcompat.widget.AppCompatTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/c_FF4E4E"
        android:gravity="center_horizontal"
        android:text="22222222"
        android:textColor="@color/c_F"
        android:textSize="12sp"
        app:layout_constrainedHeight="true"
        app:layout_constrainedWidth="true"
        app:layout_constraintDimensionRatio="w,1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_min="wrap" />

Solution

  • Try this code:

    <androidx.appcompat.widget.AppCompatTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constrainedHeight="true"
        app:layout_constraintHeight_max="20dp"
        app:layout_constraintDimensionRatio="1"
        android:gravity="center_horizontal"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>