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.

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:

implementation ''

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_constraintWidth_percent and 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:

    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 android:layout_width to 0dp above.

Similarly, if you want to set the height of the button to 20% of screen, you can do it like this:

    android:layout_constraintWidth_percent="0.2" />

See! we have specified android:layout_height to 0dp this time as we want button to use height as percentage.

If you liked this article, you can read my new articles below:

profile card
Wajahat Karim
🌍 Making the world a better place, one app at a time.
🔥 Google Developer Expert (GDE) in Android . 📱 Professional Android Developer with ~10 years experience. 💻 Creator of various Open Source libraries on Android . 📝 Author of two technical books and 100+ articles on Android. 🎤 A passionate Public Speaker giving talks all over the world.
Author's picture

Wajahat Karim

🔥 Google Dev Expert (GDE) in Android .
📱 Android Dev. 💻 Open Source Contributor . 📝 Technical Writer . 🎤 Public Speaker

Senior Android Developer

Karachi, Pakistan