Junior — Middle
Can you explain what the onLayout method does in the View class?
sobes.tech AI
Answer from AI
The onLayout method in the View class is responsible for positioning child elements within the View itself. It is called by the Android system after measuring the View's dimensions (after onMeasure) and determines the exact coordinates (position and size) for each child element.
In the base View class, this method is usually not overridden, but in custom ViewGroups (such as LinearLayout or RelativeLayout), it is implemented to arrange child Views in the desired locations.
Example of overriding onLayout in a custom ViewGroup:
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int childLeft = left;
int childTop = top;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
int width = child.getMeasuredWidth();
int height = child.getMeasuredHeight();
child.layout(childLeft, childTop, childLeft + width, childTop + height);
childTop += height; // position child elements vertically
}
}
Thus, onLayout determines where and how the child elements will be placed inside the container.