Percentage Width/Height using Constraint Layout
UPDATE: I’ve started a new articlw series on ConstraintLayout to discuss tips and tricks regularly. Here’s the first article about it.
Save time and improve productivity by using Live Templates for ConstraintLa...
Constraint Layout 1.1 was recently released as stable and there’s a lot to love. A complete overhaul of optimization makes most layouts run even faster than before and new features like barriers and groups make real-world designs simple! You can add it using this line in your android projects:
There has been lots of new features in version 1.1, but we will talk about the percentage feature here. In Constraint Layout 1.0 making a view take up a percentage of the screen required making two guidelines. In Constraint Layout 1.1 it’s been made simpler by allowing you to easily constrain any view to a percentage width or height.
Isn’t this fantastic? All views support
layout_constraintHeight_percent attributes. These will cause the constraint to be fixed at a percentage of the available space. So making a
Button or a
TextView expand to fill a percent of the screen can be done with a few lines of XML.
For example, if you want to set the width of the button to 70% of screen, you can do it like this:
<Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_constraintWidth_percent="0.7" />
Please note that you will have to put the dimension should be used as percentage to
0dp as we have specified
Similarly, if you want to set the height of the button to 20% of screen, you can do it like this:
<Button android:layout_width="wrap_content" android:layout_height="0dp" android:layout_constraintWidth_percent="0.2" />
See! we have specified
0dp this time as we want button to use height as percentage.
If you liked this article, you can read my new articles below:
Learn how to create a chat app in Android with CometChat Pro
A Year of Open Source, Public Speaking, New Job, New House, and the Big NEW...
Wajahat Karim is a graduate from NUST, Islamabad, an experienced mobile developer, an active open source contributor, and co-author of two books Learning Android Intents and Mastering Android Game Development with Unity. In his spare time, he likes to spend time with his family, do experiments on coding, loves to write about lots of things (mostly on blog and medium) and is passionate contributor to open source. In June 2018, one of his library became #1 on Github Trending. His libraries have about 2000 stars on Github and are being used in various apps by the developers all around the globe. Follow him on Twitter and Medium to get more updates about his work in Writing, Android and Open Source.
Also, if you have any questions you’d like him to answer, contact him through his website at wajahatkarim.com with DEAR WAJAHAT in the subject line.