Use a fixed aspect ratio with the Percent Support Library 23.1
Pro-tip by +Ian Lake
The Percent Support Library (https://goo.gl/KbnO7W
) makes it easy to set dimensions and margins in terms of a percentage of the overall space. In the 23.1 release (http://goo.gl/Ohd5Sy
), it also gained the ability to set a custom aspect ratio
This allows you to set only a single dimension, such as only the width, and the height will be automatically determined based on the aspect ratio you’ve defined, whether it is 4:3 or 16:9 or even a square 1:1 aspect ratio.
So building a navigation drawer header with a 16:9 background image would look like:
<ImageView app:layout_widthPercent="100%" app:layout_aspectRatio="178%"
<!-- The rest of your layout -->
You’ll note we use layout_widthPercent
instead of layout_width
- this ensures that the height is not erroneously set to 0dp before the first layout pass is done and ensures the aspect ratio is always correctly computed based on the current width.
So how did a 16:9 aspect ratio turn into 178%? Our target 16:9 aspect ratio can also be expressed as a 1.78:1 ratio or equivalently, a width 178% of the height. This is the format the layout_aspectRatio
Of course, you can also define the aspect ratio in separate XML files with code such as:
<item name="header_aspectRatio" type="fraction">178%</item>
This makes it possible to change or reuse them across different form factors or layouts.
Material design designates a number of ratio keylines (http://goo.gl/OHeq6x
) which you can use in your app, but you could also consider using this for list items (where you may be using ?android:attr/listPreferredItemHeight
) with items such as a profile image or video thumbnail for a fixed aspect ratio.
You’ll be able to use this with PercentFrameLayout
, or through any custom ViewGroup using PercentLayoutHelper