What are widthMeasureSpec and heightMeasureSpec in Android custom Views?

widthMeasureSpec and heightMeasureSpec are compound variables. Meaning while they are just plain old ints, they actually contain two separate pieces of data.

The first part of data stored in these variables is the available space (in pixels) for the given dimension.

You can extract this data using this convenience method:

int widthPixels = View.MeasureSpec.getSize( widthMeasureSpec );

The second piece of data is the measure mode, it is stored in the higher order bits of the int, and is one of these possible values:

View.MeasureSpec.UNSPECIFIED
View.MeasureSpec.AT_MOST
View.MeasureSpec.EXACTLY

You can extract the value with this convenience method:

int widthMode = View.MeasureSpec.getMode( widthMeasureSpec );

You can do some logic, change one or both of these, and then create a new meassureSpec using the last convenience method:

int newWidthSpec = View.MeasureSpec.makeMeasureSpec( widthPixels, widthMode  );

And pass that on down to your children, usually by calling super.onMeasure( widthMeasureSpec, heightMeasureSpec );

In onMeasure() the MeasureSpec pattern serves the purpose of passing in the maximum allowed space your view and it's children are allowed to occupy. It also uses the spec mode as a way of placing some additional constrains on the child views, informing them on how they are allowed to use the available space.

A good example of how this is used is Padding. ViewGroups take the available width and height, and subtract out their padding, and then create a new meassureSpec, thus passing a slightly smaller area to their children.


This article will be helpful for you. I'm answering your question from the context of the article.

1. What is the actual meaning of those parameters?

Answer:

widthMeasureSpec Horizontal space requirements as imposed by the parent view to the child view.

heightMeasureSpec Vertical space requirements as imposed by the parent view to the child view

2. What are their initial values?

Answer:

when MODE_SHIFT = 30 when values are -

MeasureSpec.UNSPECIFIED = 0 << MODE_SHIFT = 0

MeasureSpec.EXACTLY = 1 << MODE_SHIFT = 1073741824

MeasureSpec.AT_MOST = 2 << MODE_SHIFT = 2147483648

3. With what values they are called if the custom view that I am creating is the parent view for my activity?

Answer: It will depend on what height and width you give in the parent view. You will get a good insight about it in the last part of the article which also shows a chart below I mentioned -

enter image description here

Tags:

Android