Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set fixed aspect ratio for a layout in Android

Tags:

android

I am trying to set the width of the layout to "fill_parent" while having the height of the view just the same length, to make the layout a square.

Any suggestions will be appreciate, thanks in advance! :D

like image 268
Bolton Avatar asked Sep 07 '12 03:09

Bolton


2 Answers

With introduction of ConstraintLayout you don't have to write either a single line of code or use third-parties or rely on PercentFrameLayout which were deprecated in 26.0.0.

Here's the example of how to keep 1:1 aspect ratio for your layout using ConstraintLayout:

<android.support.constraint.ConstraintLayout     android:layout_width="match_parent"     android:layout_height="match_parent">      <FrameLayout         android:layout_width="0dp"         android:layout_height="0dp"         android:layout_marginEnd="0dp"         android:layout_marginStart="0dp"         android:layout_marginTop="0dp"         android:background="@android:color/black"         app:layout_constraintDimensionRatio="H,1:1"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent">      </FrameLayout>  </android.support.constraint.ConstraintLayout> 

Or instead of editing your XML file, you can edit your layout directly in Layout Editor:

Layout Editor

like image 169
Eugene Brusov Avatar answered Oct 07 '22 20:10

Eugene Brusov


In your build.gradle add:

compile 'com.android.support:percent:23.1.1' 

and in your layout.xml wrap whatever view or viewgroup you want to to follow a ratio inside a PercentFrameLayout where:

android:layout_width="match_parent" android:layout_height="wrap_content" 

and then for the view or viewgroup you want to to follow a ratio replace android:layout_width and android:layout_height:

    app:layout_aspectRatio="178%"     app:layout_widthPercent="100%" 

and you have a view or viewgroup where the aspect ratio is 16:9 (1.78:1) with the width matching the parent and the height adjusted accordingly.

Note: It's important you remove the normal width and height properties. Lint will complain, but it'll work.

like image 28
Espen Riskedal Avatar answered Oct 07 '22 20:10

Espen Riskedal