Search code examples
javaandroidviewonmeasure

How can MeasureSpec.getMode() extract a mode from an integer value?


I'm on chapter 4 of Professional Android 4 Application Development, and it's telling me that both a size value and a mode are extracted from the widthMeasureSpec and heightMeasureSpec values passed to the onMeasure() method of a custom view. Would those not have to be some other data structure than an integer primitive to accomplish this? Are these integers encoded in such a way that it would be possible to ever manually override their values?


Solution

  • The mode is either EXACTLY, AT_MOST, or UNSPECIFIED. So technically it only takes two bits to store the mode. If you look at their values, EXACTLY is 0x80000000, AT_MOST is 0x40000000 and UNSPECIFIED is 0x00000000. They are taking the top two bits of the int and ORing them with the size to get the MeasureSpec. This is probably a holdover from early Android when devices really didn't have a lot of memory, so they tried to conserve wherever they could.