TechBuzzPro

How to Create Custom Views in Android

· 6 min read · Phones & Tablets

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. Decide the type of custom view. If you are combining existing widgets (an icon plus two labels, for example), extend ViewGroup or use a compound view that inflates a layout. If you are drawing shapes, text, or graphics from scratch, extend View and override onDraw(). Choosing the wrong base class is the most common reason a custom view feels harder than it should.
  2. 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 @JvmOverloads annotation (or the equivalent three constructors in Java) ensures the view can be inflated from XML, which requires the (Context, AttributeSet) constructor.
  3. Set up your paint objects and dimensions. In the class body, create a Paint for each thing you draw and initialise it in an init block or constructor. Convert dp values to pixels with resources.displayMetrics.density so the view looks the same across screen densities. Avoid allocating Paint or Rect objects inside onDraw(), because that method runs on every frame and allocations cause jank.
  4. 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 in onDraw(), and store the results in fields.
  5. Override onDraw(canvas: Canvas) and draw. Call super.onDraw(canvas) only if the parent class draws something you want to keep. Then use canvas.drawCircle(), drawRect(), drawText(), or drawPath() with your prepared paint. Keep the method free of object creation and heavy logic.
  6. Handle measurement if the view must size itself. Override onMeasure(widthMeasureSpec, heightMeasureSpec), read the modes with MeasureSpec.getMode() and sizes with MeasureSpec.getSize(), then call setMeasuredDimension() with your desired width and height. Respect AT_MOST and EXACTLY so the view behaves inside wrap_content and fixed-size parents.
  7. Add custom XML attributes (optional). Declare them in res/values/attrs.xml inside a <declare-styleable> block, then read them in the constructor with context.obtainStyledAttributes(attrs, R.styleable.YourView). Always call recycle() on the TypedArray when done. This lets designers set colours or sizes directly in the layout file.
  8. Make the view interactive if needed. Override onTouchEvent() for custom gestures, or call setOnClickListener() from outside if simple taps are enough. For accessibility, call setContentDescription() and ensure touch targets are at least 48dp.
  9. 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 with CircleView(context) and add it to a parent ViewGroup. Preview it in Android Studio's layout editor to catch inflation errors early.
  10. 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 AttributeSet constructor. XML inflation fails with an InflateException if the view cannot be constructed from a Context and AttributeSet.
  • Allocating objects in onDraw(). Creating Paint, Path, or Rect on every frame causes stutter and garbage collection pauses.
  • Ignoring onMeasure(). A view that never calls setMeasuredDimension() or mishandles AT_MOST can 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 ViewCompat and CanvasCompat helpers where available to keep behaviour consistent across API levels.
  • Enable setWillNotDraw(false) on custom ViewGroup subclasses if you override onDraw(), otherwise the system may skip drawing.
  • Keep a single Paint per visual element and mutate its properties between draws instead of creating new ones.
  • Use @JvmOverloads in 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.