Search code examples
androidlayoutaspect-ratio

Aspect ratio equivalent for Android?


I would like to add a view with an leading/trailing margin of 12dp and an aspect ratio of 4:1 of the screen width. Coming from an iOS background, I would this to get that result:

enter image description here

Now I want to do the same with Android, and I'm only stuck with the aspect ratio:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:layout_width="match_parent"
        <!-- android:layout_height="{what to do here?}" -->
        android:layout_centerInParent="true"
        android:layout_marginStart="12dp"
        android:layout_marginEnd="12dp"
        android:background="@color/my_blue_color" />

</RelativeLayout>

What do I have to change here about the view's height to get the expected ratio?

Thanks for your help.


Solution

  • You can achieve this by using ConstraintLayout

    Add Dependency first

    dependencies {
        implementation'com.android.support.constraint:constraint-layout:1.0.2'
    }
    

    Here is an example

         <?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"
                tools:context="com.burhanrashid52.unittestsample.MainActivity">
    
    
                <View
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    android:layout_marginEnd="12dp"
                    android:layout_marginStart="12dp"
                    android:layout_marginTop="12dp"
                    android:background="@android:color/holo_blue_dark"
                    app:layout_constraintDimensionRatio="w,1:4"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />
    
    
          </android.support.constraint.ConstraintLayout>
    

    Output