How to set fixed aspect ratio for a layout in Android
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.
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: