Custom Views
Draw custom UI components from scratch. Extend View, implement onMeasure and onDraw with Canvas and Paint, define custom XML attributes, and build compound views.
Why Custom Views?
Sometimes the built-in Android views don't do exactly what you need. Custom views let you:
- Draw shapes, graphs, progress rings, or charts that don't exist in the SDK
- Create branded UI components used consistently throughout the app
- Combine several views into one reusable component (Compound View)
- Achieve performance by eliminating nested layout hierarchies
Extending View
Create a custom view by extending View (or a subclass like ImageView). Override the required constructor:
class CircleProgressView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
var progress: Float = 0f
set(value) {
field = value.coerceIn(0f, 100f)
invalidate() // trigger redraw
}
// onMeasure and onDraw go here
}