Junior — Middle
How does the onMeasure method get called in the View component in Android?
sobes.tech AI
Answer from AI
In Android, the onMeasure method of a View component is called by the system during the measurement process before the View is displayed on the screen.
The call process is as follows:
- The parent ViewGroup calls the measure(int widthMeasureSpec, int heightMeasureSpec) method for its child Views.
- Inside the measure method, onMeasure is called with the provided measurement parameters.
- In onMeasure, the View must determine its size by calling setMeasuredDimension(width, height).
Thus, onMeasure is invoked by the system during the layout measurement pass, allowing the View to determine how much space it needs.
If you override onMeasure, it is important to call setMeasuredDimension; otherwise, the View's size will be 0x0.
Example of overriding:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 100; // for example, desired width
int desiredHeight = 100; // desired height
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
width = Math.min(desiredWidth, widthSize);
} else {
width = desiredWidth;
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(desiredHeight, heightSize);
} else {
height = desiredHeight;
}
setMeasuredDimension(width, height);
}