Custom Views
A custom View on Android is needed when the stock widgets are not enough — your own chart, your own layout container, precise measuring for a ratio. The key is to understand that the system draws any View in strictly three phases: first it asks for the desired size (onMeasure), then it tells the final position (onLayout), then it asks you to draw (onDraw). Every custom-view mechanism plugs into its own phase.
The main traps are not about syntax but about the phase and the mode. Setting the size in onDraw is too late: the parent has already computed the layout from what onMeasure returned. And returning a raw size from onMeasure without reading the MeasureSpec mode breaks wrap_content. The full map is in the layers below.
Topic map
- Custom view lifecycle — the three phases
onMeasure→onLayout→onDrawand what to do in each. - MeasureSpec — how the parent passes the size and mode (
EXACTLY/AT_MOST/UNSPECIFIED) and how to read them. - Fixed aspect ratio — how to keep a 4:3 ratio via
onMeasure. - Text truncation — how to shrink the right field when width runs out.
Common traps
| Mistake | Consequence |
|---|---|
Setting the size in onLayout or onDraw | Too late — the parent already laid the view out from onMeasure |
Returning a raw getSize(spec), ignoring the mode | wrap_content stretches to the whole parent |
Allocating Paint/Rect inside onDraw | Allocations on every frame — jank while drawing |
| Hard-coding a pixel height instead of deriving it from the width | The ratio breaks at a different parent width |
| Splitting two fields' width with equal weights | Both fields shrink, not just the intended one |
Interview relevance
Custom views check whether you understand Android's drawing pipeline, not just the widget API. A candidate who names the three phases in order and says "size in onMeasure via setMeasuredDimension" immediately gets ahead of one who "draws everything in onDraw".
Typical checks:
- The order and purpose of
onMeasure,onLayout,onDraw. - What a
MeasureSpecis and its three modes. - How to keep an aspect ratio and why it is done in
onMeasure. - How to shrink the right one of two fields and the role of
ellipsize.
Common wrong answer: "the view's size is set in onDraw / onLayout". In fact the desired size is reported only in onMeasure via setMeasuredDimension; onLayout positions children, and onDraw draws by the already computed sizes.