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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…