Jono0 Jono0 - 28 days ago 6
Android Question

ConstraintLayout doesn't respect max width/height in combination with DimensionRatio

The view below needs to be square. I also want to the view to be restricted to a certain size. Somehow the ConstraintLayout is ignoring the max width/height property when this is used in combination with dimensionRatio on the same element.

<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">
<View
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="@+id/guideline_top"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintLeft_toLeftOf="@+id/guideline_left"
app:layout_constraintRight_toRightOf="@+id/guideline_right"
app:layout_constraintBottom_toBottomOf="@+id/guideline_bottom"
app:layout_constraintWidth_max="100dp"
app:layout_constraintHeight_max="100dp"/>


At the moment I'm using a workaround by putting the View in a container as shown below. But I'd rather keep my layout-hierarchy as flat as possible.

<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">
<android.support.constraint.ConstraintLayout
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="@+id/guideline_top"
app:layout_constraintLeft_toLeftOf="@+id/guideline_left"
app:layout_constraintRight_toRightOf="@+id/guideline_right"
app:layout_constraintBottom_toBottomOf="@+id/guideline_bottom"
app:layout_constraintWidth_max="100dp"
app:layout_constraintHeight_max="100dp">
<View
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>


Is this is a restriction in the constraintlayout that you can't use max width/height in combination with dimension ratio?

I'm using ConstraintLayout v1.0.2.

Answer Source

Specify either

`app:layout_constraintDimensionRatio="H,1:1"` 

or

`app:layout_constraintDimensionRatio="W,1:1"`

This should causeConstraintLayout pick up your max width and height. See "Ratios" in the doc.