ConstraintLayout - proportional width/height to self?

dor506 picture dor506 · Apr 3, 2018 · Viewed 12.5k times · Source

I'm trying to figure out how to achieve the following behaviour using constraint layout:

  1. Place a view in the center of the ConstraintLayout parent
  2. Make the view width to be half of the parent's width
  3. Make the view height equals to its width

(i.e - place a square in the center)

I tried to use this combination:

  android:layout_width="0dp"
  android:layout_height="0dp"
  app:layout_constraintBottom_toBottomOf="parent"
  app:layout_constraintEnd_toEndOf="parent"
  app:layout_constraintStart_toStartOf="parent"
  app:layout_constraintTop_toTopOf="parent"
  app:layout_constraintDimensionRatio="2:1"

But I'm not sure how to continue from here

Answer

serg3z picture serg3z · Apr 4, 2018

You can do without Guideline it is easy.

Just use app:layout_constraintWidth_percent="0.5"

It is work in version ConstraintLayout:1.1.0-beta5 and later.

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/img_icon"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@color/dark_red"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_percent="0.5" />

</android.support.constraint.ConstraintLayout>

enter image description here