Junior
Are you familiar with the View lifecycle in Android?
sobes.tech AI
Answer from AI
Yes, I am familiar.
The lifecycle of a View consists of several key stages:
- Measurement: Determines the size of the View and its children. It occurs in two passes:
measure(int widthMeasureSpec, int heightMeasureSpec): Performs measurement.onMeasure(int widthMeasureSpec, int heightMeasureSpec): Overridden to implement measurement logic.
- Layout: Determines the position of the View and its children. It occurs in one pass:
layout(int l, int t, int r, int b): Sets the position.onLayout(boolean changed, int l, int t, int r, int b): Overridden to implement layout logic.
- Drawing: Renders the View and its children on the Canvas. It occurs in one pass:
draw(Canvas canvas): Performs drawing.onDraw(Canvas canvas): Overridden to implement drawing logic.
- Attach/Detach: Indicates whether the View is attached to the window or detached.
onAttachedToWindow(): Called when attached.onDetachedFromWindow(): Called when detached.
During the lifecycle, requests for re-measurement (requestLayout()) or redraw (invalidate()) may occur, leading to the repetition of the respective stages.
For custom Views, the methods onMeasure, onLayout, and onDraw are most often overridden.
Key methods table:
| Stage | Measurement Method | Layout Method | Drawing Method | Attach/Detach Method |
|---|---|---|---|---|
| Process | measure() |
layout() |
draw() |
|
| Override | onMeasure() |
onLayout() |
onDraw() |
onAttachedToWindow(), onDetachedFromWindow() |
Example of overriding onMeasure in a custom View:
// In a custom View
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Get measurement mode and size
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int desiredWidth = 100; // Desired width of the View
int desiredHeight = 100; // Desired height of the View
int width;
int height;
// Handle different measurement modes
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
width = Math.min(desiredWidth, widthSize);
} else { // MeasureSpec.UNSPECIFIED
width = desiredWidth;
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(desiredHeight, heightSize);
} else { // MeasureSpec.UNSPECIFIED
height = desiredHeight;
}
// Set the final size of the View
setMeasuredDimension(width, height);
}