Android Custom Views: Beyond the Standard Library

A custom view gives you full control over a UI component's drawing and interaction. Use it for unique elements like charts or radial menus that standard widgets can't handle. The footgun is building one when composing existing views would be simpler.
WHY IT EXISTS: The standard Android UI toolkit provides powerful components like Button and TextView, but it can't cover every possible design. Custom views exist to fill this gap, allowing developers to create unique, app-specific UI elements that are fully integrated into the Android layout system.
THE MENTAL MODEL: Think of building a custom view as creating your own specialized tool. You can either modify an existing tool (by extending a class like Button) or forge a new one from raw materials (by extending the base View class). You are responsible for telling Android exactly how to measure it, lay it out, draw it, and handle user input for it.
HOW IT WORKS: Creating a custom view typically involves three key steps. First, you extend the View class or one of its subclasses. Second, you override core lifecycle methods: onMeasure() to define its size, onDraw() to render its appearance on a Canvas, and onTouchEvent() to handle user interaction. Third, you can define custom XML attributes (using a declare-styleable resource) to make your view configurable in layout files, just like standard Android widgets.
WHEN TO USE IT: Use a custom view when you need a UI element with a look or behavior that cannot be achieved by combining or styling existing widgets. Good examples include custom data visualizations like graphs and charts, unique interactive elements like a rotary dial or a joystick, or highly optimized components for performance-critical UIs like a game board.
WHEN NOT TO USE IT: Avoid creating a custom view for simple composition. If you just need to group a TextView and an ImageView together, creating a reusable layout with a ConstraintLayout or a custom ViewGroup is far simpler and more maintainable. Also, if you only need a custom shape or background, a custom Drawable is often a much lighter-weight solution than a full custom view.
ONE CANONICAL EXAMPLE: A common first custom view is a circle with a number in the center, like a notification badge. You would extend View, override onMeasure() to request a square space, and in onDraw(), you'd use canvas.drawCircle() to draw the background and canvas.drawText() to draw the number. You could add custom attributes for the circle's color and the text value.
Read the original → developer.android.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.