If you write a lot of UI layouts for Android and your goal is making a responsive Android App, you surely faced the need of having something like “match_parent” or “wrap_content” in your Android Dimension Resources.
You might think of typing this:
But it doesn’t work like this. And the compiler will let you know that it doesn’t like what you’ve typed. 😡
We’ve to go a little bit deeper and see how the Android Source Code manages LayoutParams.
Looking to the source code you can see that:
MATCH_PARENT and WRAP_CONTENT are two static final ints and they’re set respectively to -1 and -2.
When you set the width or the height to a view, the value is stored in an int (using px as a measurement unit).
Px isn’t the only measurement unit. Android uses a lot of them (dp, sp, mm) but most of them depends on other things such as the screen density. Px is density independent and this is good for us!
At this point you can try putting -1px in place of match_parent in one of your layouts and it will work as expected!
Observing this we can say that:
- MATCH_PARENT equals to -1px,
- WRAP_CONTENT equals to -2px. Nice, uh?
What you can do using this trick?
Using this trick you can build responsive apps exploiting the dimension resources xml file and resize things to reach your screen boundaries without recurring to Java but only using xml.
Go and spread the word ‘cause we need to #BuildBetterApps!