Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConstraintLayout - proportional width/height to self?

Tags:

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

like image 756
dor506 Avatar asked Apr 03 '18 21:04

dor506


People also ask

What is ConstraintLayout guideline?

A Guideline can be either horizontal or vertical: Vertical Guidelines have a width of zero and the height of their ConstraintLayout parent. Horizontal Guidelines have a height of zero and the width of their ConstraintLayout parent.

Can we use ConstraintLayout inside ConstraintLayout?

You can use a ConstraintLayout in an other ConstraintLayout but you need to respect some rules. All direct childs of a ConstraintLayout should have constraint on left,top, right and bottom.

What is Layout_constraintdimensionratio?

A ConstraintLayout is a ViewGroup which allows you to Position and size Views in a flexible way. It is basically RelativeLayout on Steriods. The Views will be positioned and sized w.r.t other Views with the Use of Constraints.

Can we use linear layout in ConstraintLayout?

You can create linear layouts now with ConstraintLayout by constraining the sides of each element with each other. The quick way of creating these layouts is to select all the views together and right click to center horizontally or vertically.


1 Answers

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

like image 129
serg3z Avatar answered Sep 30 '22 18:09

serg3z