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:
- Create a new class that extends View.
- Create custom constructor(s).
- Override
onMeasure()
, and the default implementation returns a size of 100 x 100. - Override
onDraw()
, and the default implementation draws nothing. - Define custom methods and listeners (such as on<Event>()).
- Implement custom functionality.
Tip
While overriding onMeasure()
and onDraw()
is not strictly required, the default behavior is likely not what you would want.
Getting ready
Start a new project in Android Studio and call it CustomView
. Use the default wizard options, including the Phone & Tablet SDK and select Empty...