Appendix A. Relative and Grid Layouts: Meet the Relatives

There are two more layouts you will often meet in Androidville. In this book we’ve concentrated on using simple linear and frame layouts, and introduced you to Android’s new constraint layout. But there are two more layouts we’d like you to know about: relative layouts and grid layouts. They’ve largely been superseded by the constraint layout, but we have a soft spot for them, and we think they’ll stay around for a few more years.

A relative layout displays views in relative positions

A relative layout allows you to position views relative to their parent layout, or relative to other views in the layout.

You define a relative layout using the <RelativeLayout> element like this:

Positioning views relative to the parent layout

If you want a view to always appear in a particular position on the screen, irrespective of the screen size or orientation, you need to position the view relative to its parent. As an example, here’s how you’d make sure a button always appears in the top-center of the layout:

The lines of code:

android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"

mean that the top edge of the button is aligned ...

Get Head First Android Development, 2nd 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.