Will Chan
Will Chan

Reputation: 63

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

Upvotes: 0

Views: 918

Answers (2)

Mike087
Mike087

Reputation: 491

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

Upvotes: 1

Denis
Denis

Reputation: 81

As a variant you can try to add a LayoutChangeListener and inside of it check the view size and then set app:layout_constraintDimensionRatio property for the view

Upvotes: 0

Related Questions