ConstraintLayout layout_constraintDimensionRatio not working

pistolcaffe picture pistolcaffe · May 20, 2017 · Viewed 16.3k times · Source

I used constraintLayout and layout_constraintDimensionRatio = "1:1" (width is warp_content , height is 0dp (match_constraint))

As a result, I expected width and height to be 1: 1 but not working.

what is wrong??

I attached code and screenshot.

<?xml version="1.0" encoding="utf-8"?>
<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">

    <TextView
        android:id="@+id/t1"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:background="@android:color/holo_blue_bright"
        android:gravity="center"
        android:text="Hello World!11"
        app:layout_constraintDimensionRatio="1:1" />

</android.support.constraint.ConstraintLayout>

screenshot

I quote android developer site about Constraintlayout. https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html#DimensionConstraints

"Ratio :: You can also define one dimension of a widget as a ratio of the other one. In order to do that, you need to have at least one constrained dimension be set to 0dp (i.e., MATCH_CONSTRAINT), and set the attribute layout_constraintDimentionRatio to a given ratio. For example:

     <Button android:layout_width="wrap_content"
               android:layout_height="0dp"
               app:layout_constraintDimensionRatio="1:1" />

will set the height of the button to be the same as its width."

--> but i was not working.

Answer

Rami Jemli picture Rami Jemli · May 23, 2017

You forget to add your constraints

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

    <TextView
        android:id="@+id/t1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:background="@android:color/holo_blue_bright"
        android:gravity="center"
        android:text="Hello World!11"
        app:layout_constraintDimensionRatio="1" />

</android.support.constraint.ConstraintLayout>

0dp is only applied to the child views of ConstraintLayout. Any view should apply the attribute rules of its parent.