O'Reilly logo

Building Android UIs with Custom Views by Raimon Ràfols Montané

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Extending ViewGroup

The process to create a custom layout is quite similar to creating a custom view. We've got to create a class that extends from ViewGroup instead of view, create the appropriate constructors, implement the onMeasure() method, and override the onLayout() method rather than the onDraw() method.

Let's create a very simple custom layout; it will add elements to the right of the previous element until it doesn't fit on the screen, then it'll start a new row, using the higher element to calculate where this new row will start and avoid any overlapping between views.

Adding random sized views, where each view has a red background, will look as follows:

First, let's create a class that extends from ViewGroup:

public class CustomLayout ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required