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
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With