Home > Software design >  How to constraint a view min width equal to height in ConstraintLayout?
How to constraint a view min width equal to height in ConstraintLayout?

Time:07-14

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?

CodePudding user response:

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

CodePudding user response:

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