Chapter 3. Custom Components

While both Android and iOS provide a large number of widgets and components out of the box, there’s not always parity, and it’s very likely you’ll want to create your own at some point. You might want a date or color picker with custom look or behavior, a switch or toggle with a built-in label, data visualization components like charts and graphs, or something as simple as a configurable label and icon that’s suited just for your app.

Whatever the need, there’s a pretty good chance you can create it in either framework—but the process is very different and can be surprisingly arcane.

Tasks

In this chapter, you’ll learn:

  1. How to create a custom view.

  2. How to use a custom view.

Android

Since most layouts in Android apps are created with XML data, getting your custom component to accept and react appropriately to arbitrary properties is something you’ll probably want to offer. For example, if you were to create a custom color picker, you’d probably want to offer a default color to start with, or perhaps even a specific color space like HSL or RGB.

Since XML resources are compiled, you’ll need to make sure the system recognizes the extra properties you allow on your component and what values are valid. For example, if you add a color attribute, you wouldn’t want to accept a dimension value—you’d want only valid colors, or perhaps color resource IDs, to be accepted. If a user tries to enter an invalid value format, the program will fail to compile, ...

Get Native Mobile Development 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.