Creating a custom component

As we have seen in previous recipes, the Android SDK provides a wide range of components. But what happens when you can't find a prebuilt component that fits your unique needs? You can always create your own!

In this recipe, we will walk through creating a custom component that derives from the View class, just like the built-in widgets. Here's a high-level overview:

  1. Create a new class that extends View.
  2. Create custom constructor(s).
  3. Override onMeasure(), and the default implementation returns a size of 100 x 100.
  4. Override onDraw(), and the default implementation draws nothing.
  5. Define custom methods and listeners (such as on<Event>()).
  6. Implement custom functionality.

Tip

While overriding onMeasure() and onDraw() is not strictly ...

Get Android Application Development Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.