How to Create Custom Views in Android
In this article
To create a custom view in Android, you extend the View class (or a subclass like TextView or ViewGroup), override the constructors and onDraw() or onMeasure() as needed, then add the view to a layout or instantiate it in code. The exact steps depend on whether you are drawing something new or composing existing widgets. This guide walks through both approaches, the lifecycle methods that matter, and the mistakes that cause blank or mis-sized views.
What You'll Need
- Android Studio with an empty or existing project targeting a recent API level.
- Basic familiarity with Kotlin or Java and XML layouts.
- A physical device or emulator to preview and test the view.
Step-by-Step
- Decide the type of custom view. If you are combining existing widgets (an icon plus two labels, for example), extend
ViewGroupor use a compound view that inflates a layout. If you are drawing shapes, text, or graphics from scratch, extendViewand overrideonDraw(). Choosing the wrong base class is the most common reason a custom view feels harder than it should. - Create a new Kotlin or Java class that extends the base class. For a drawn view, start with
class CircleView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr). The@JvmOverloadsannotation (or the equivalent three constructors in Java) ensures the view can be inflated from XML, which requires the(Context, AttributeSet)constructor. - Set up your paint objects and dimensions. In the class body, create a
Paintfor each thing you draw and initialise it in aninitblock or constructor. Convert dp values to pixels withresources.displayMetrics.densityso the view looks the same across screen densities. Avoid allocatingPaintorRectobjects insideonDraw(), because that method runs on every frame and allocations cause jank. - Override
onSizeChanged()if your drawing depends on the view's size. This callback fires when the view is first measured and whenever its dimensions change. Compute any derived geometry (centre point, radius, path) here rather than inonDraw(), and store the results in fields. - Override
onDraw(canvas: Canvas)and draw. Callsuper.onDraw(canvas)only if the parent class draws something you want to keep. Then usecanvas.drawCircle(),drawRect(),drawText(), ordrawPath()with your prepared paint. Keep the method free of object creation and heavy logic. - Handle measurement if the view must size itself. Override
onMeasure(widthMeasureSpec, heightMeasureSpec), read the modes withMeasureSpec.getMode()and sizes withMeasureSpec.getSize(), then callsetMeasuredDimension()with your desired width and height. RespectAT_MOSTandEXACTLYso the view behaves insidewrap_contentand fixed-size parents. - Add custom XML attributes (optional). Declare them in
res/values/attrs.xmlinside a<declare-styleable>block, then read them in the constructor withcontext.obtainStyledAttributes(attrs, R.styleable.YourView). Always callrecycle()on theTypedArraywhen done. This lets designers set colours or sizes directly in the layout file. - Make the view interactive if needed. Override
onTouchEvent()for custom gestures, or callsetOnClickListener()from outside if simple taps are enough. For accessibility, callsetContentDescription()and ensure touch targets are at least 48dp. - Use the view in a layout or in code. In XML, write the fully qualified class name:
<com.example.myapp.CircleView android:layout_width="100dp" android:layout_height="100dp" />. In code, instantiate it withCircleView(context)and add it to a parentViewGroup. Preview it in Android Studio's layout editor to catch inflation errors early. - Test across configurations. Rotate the device, change font scale and dark mode, and try different screen sizes. If the view uses colours, read them from theme attributes or resource colours rather than hard-coding hex values, so it adapts automatically.
Common Mistakes
- Forgetting the
AttributeSetconstructor. XML inflation fails with anInflateExceptionif the view cannot be constructed from aContextandAttributeSet. - Allocating objects in
onDraw(). CreatingPaint,Path, orRecton every frame causes stutter and garbage collection pauses. - Ignoring
onMeasure(). A view that never callssetMeasuredDimension()or mishandlesAT_MOSTcan collapse to zero size or overflow its parent. - Hard-coding pixel values. Using raw pixels instead of dp makes the view look tiny on high-density screens and huge on low-density ones.
- Not recycling the
TypedArray. Leaking styled attributes is a slow resource leak that is easy to miss in review.
Tips
- Use
ViewCompatandCanvasCompathelpers where available to keep behaviour consistent across API levels. - Enable
setWillNotDraw(false)on customViewGroupsubclasses if you overrideonDraw(), otherwise the system may skip drawing. - Keep a single
Paintper visual element and mutate its properties between draws instead of creating new ones. - Use
@JvmOverloadsin Kotlin to generate all three constructors automatically. - Add a preview by implementing
onMeasure()sensibly and using the layout editor's custom view preview, or create a small sample layout that uses the view. - If the view will be reused, package it in a library module so other projects can depend on it without copying code.
Troubleshooting
If the view does not appear, first check that the class name in XML matches the full package path and that the class is public. A blank area usually means onDraw() is not being called: confirm the view has non-zero dimensions and, for ViewGroup subclasses, that setWillNotDraw(false) is set. If the view crashes on inflation, verify the AttributeSet constructor exists and that any custom attributes are declared in attrs.xml. If the view is the wrong size, log the values from onMeasure() and check how AT_MOST is handled. If it looks pixelated or too small, replace raw pixel values with dp conversions. If touches do not register, ensure onTouchEvent() returns true for the events you handle, and that the view is clickable if you rely on click listeners. Finally, clean and rebuild the project after renaming or moving the class, because stale build outputs can cause confusing inflation errors.
Frequently Asked Questions
Do I need to override all three constructors?
Only the (Context, AttributeSet) constructor is strictly required for XML inflation, but providing all three (or using @JvmOverloads in Kotlin) keeps the view usable from code and with custom styles.
When should I extend ViewGroup instead of View?
Extend ViewGroup when your custom view contains child views, such as a card with an image and two text labels. Extend View when you are drawing everything yourself on a canvas.
Why is my custom view not showing in the layout preview?
The preview often fails when the view depends on runtime data or when onMeasure() does not set a size. Give the view a sensible default size in onMeasure() and avoid logic that requires a real activity context.
Can I use a custom view inside a RecyclerView item?
Yes. Inflate the item layout containing the custom view as usual. Keep onDraw() lightweight because list items are redrawn frequently while scrolling.
How do I add custom attributes to my view?
Declare a <declare-styleable> in res/values/attrs.xml, read it with obtainStyledAttributes() in the constructor, and call recycle() afterwards. Then reference the attributes in XML with your app namespace.
Does a custom view need accessibility support?
Yes, if it conveys information or accepts input. Set a content description, expose click actions through AccessibilityNodeInfo where relevant, and keep touch targets at least 48dp so screen readers and switch access work correctly.