# Android Layouts

## Overview

View Layouts are a type of View class whose primary purpose is to organize and position other view controls. These layout classes (LinearLayout, RelativeLayout, etc.) are used to display child controls, such as text controls or buttons on the screen.

Android activities (screens) use layouts as a container for view controls, and layouts can actually contain other nested layouts as well. Nearly all Android activities have layout containers similar to the way that most HTML documents use "divs" to contain other content.

There are a few very commonly used layouts and then many more specialized layouts that are used in only very particular cases. The bread and butter layouts are LinearLayout, RelativeLayout, and FrameLayout.

It's important to note the class hierarchy of these View Layouts. Each of them subclass ViewGroup, which itself subclasses View. That means it is perfectly legal to pass a layout such as LinearLayout as an argument for something that takes View as a parameter. ViewGroup also contains the nested static class LayoutParams which is used for creating or editing layouts in code. Keep in mind that each subclass of ViewGroup, such as LinearLayout, has its own nested static class LayoutParams that's a subclass of ViewGroup.LayoutParams. When creating View Layouts in code, beginners will often confuse the many different available LayoutParams classes and run into hard to catch problems.

## LinearLayout

In a linear layout, like the name suggests, all the elements are displayed in a single direction either horizontally or vertically and this behavior is specified in android:orientation which is an attribute of the node LinearLayout.

All children of a LinearLayout are displayed sequentially based on the order they are defined within the layout. A LinearLayout respects margins between children and the gravity (right, center, or left alignment) of each child.

Common view attributes you might see used in a LinearLayout:

• android:gravity - Controls the alignment of the view content (akin to text-align in CSS)
• android:layout_gravity - Controls the alignment of the view within it's parent container (akin to float in CSS)
• android:layout_weight - Specifies how much of the extra space in the layout to be allocated to a view.

Example of LinearLayout snippet:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 

Will produce something like the image below. Note that the android:orientation is set to vertical.

### Linear Layout Horizontal orientation

We will group two buttons side by side using a linear layout in horizontal orientation.

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 

And will produce something like the image below :

### Distribute Widths with Layout Weight

To distribute the width in a linear layout we use the android:layout_weight property. We can also distribute the height using the same property. Lets make the buttons take equally the same space. Notice that the android:layout_width needs to be match_parent for both buttons and theandroid:layout_weight will be used to proportionally divide the space.

And we can make the Login button take all the remaining space by just giving it the android:layout_weight=1 and wrap_content on the Sign Up button as per the picture below.

If you want to setup a part of your layout, such that, for instance, 3 buttons appear in a row, occupying equal space (or if, for instance, you want to give 4/5 space to a map and 1/5 to another component below it), LinearLayout can be used to do the trick by leveraging android:layout_weight.This works by setting the android:weightSum to a total value and then setting the android:layout_weight value for each subview to determine width distribution.

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 

{{< note title="Layout Performance" >}} For performance, when using android:layout_weight, you should set the android:layout_width=0dp so that Android does not have to calculate the width as well since its already being calculated using android:layout_weight. {{< /note >}}

Using the above XML, Login will have 2/5 of total container width and Sign Up will have 3/5 of parent width because we set the total android:weightSum to 5 and the buttons android:layout_weight property to 2 and 3 respectively.

Use caution in utilizing multiple nested LinearLayouts and/or layout_weight from a performance standpoint!

### Gravity

The android:layout_gravity is used to position the view within its parent. We can place the view to the left, right, start, bottom, center and so on.

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 

In the image below the android:layout_gravity property is used to place the Send button to the right :

### Nesting Layouts

We can nest a LinearLayout inside another LinearLayout. For performance you should limit the nesting to only 2 levels. Excessive nesting reduces drawing performance.

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 

Will look like the image below :

## RelativeLayout

In a relative layout every element arranges itself relative to other elements or a parent element. RelativeLayout positions views based on a number of directional attributes:

• Position based on siblings: layout_above, layout_below, layout_toLeftOf, layout_toRightOf
• Position based on parent: android:layout_centerHorizontal, android:layout_centerVertical
• Alignment based on siblings: layout_alignTop, layout_alignBottom, layout_alignLeft, layout_alignRight, layout_alignBaseline
• Alignment based on parent: layout_alignParentTop, layout_alignParentBottom, layout_alignParentLeft, layout_alignParentRight

An example of a RelativeLayout:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 

Will have produce a layout as below :

and another example of a Realtive Layout :

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 

Note the spinner entries are defined in the arrays.xml file as follows :

 1 2 3 4 5 6 7 8 9  Thur, 23rd Feb 2017 3:25PM 

and will produce the image as below :

Read this RelativeLayout tutorial for a more detailed overview. You can also see more about this layout by inspecting the RelativeLayout.LayoutParams docs and the official RelativeLayout guide.

We can accomplish complicated layouts with the relative layout. In the following, we have put the circle on top of the other views, and also used negative margins to accomplish it.

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26  

The background is a drawable resource, its created in the drawable folder. We will cover drawables in the styleing section.

bg.xml

 1 2 3 4 5  

Will produce the output as in the following picture :

### Using Alignment to Control Width or Height

A less understood aspect of RelativeLayout is how the use of alignment can determine width or height. It may seem counterintuitive at first about how this works, so we'll walkthrough a few examples in this section. Using this approach is especially useful in matching the widths or heights relative to other elements.

#### Example 1: How alignment can determine width

Suppose we have two buttons of varying widths:

The corresponding XML would be:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 

Suppose we also specify that the second button should be aligned left and right to the first button. If we add android:layout_alignRight="@id/button1" to the second button's XML style, the change causes the second button to expand the width to match that of the first button. In other words, the only way to meet the requirements of specifying alignment on both sides is to expand the width of the second button.

In this way, when two elements are vertically positioned above or below the other, left and right alignments will control the width. When two elements are positioned horizontally next to each other, top and bottom alignments will control the height. We'll show how height can be impacted by specifying top and bottom alignments in the next example.

#### Example 2: How alignment can determine height

Suppose we have this layout definition:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 

The corresponding preview looks like:

If we wish to match the height of the first button, we can specify layout_alignTop and layout_alignBottom on the second button.

 1 2 3 4 5 6 7 8 

The only way to fulfill this requirement is to expand the height of the second button as shown below:

## PercentRelativeLayout

PercentRelativeLayout, a recent addition to the Design Support Library, enables the ability to specify not only elements relative to each other but also the total percentage of available space. In the past, in order to position two elements next to each other with equal height, you would normally have to create a LinearLayout within a RelativeLayout. PercentRelativeLayout helps solves this issue.

The percent relative layout is available from Nuget.

The layout_width and layout_height of the PercentRelativeLayout should determine the total width and height that can be used. Any elements contained within it should specify the width and height possible using layout_heightPercent and/or layout_widthPercent. Because this library is not part of the standard Android library, note that a custom attribute app namespace being used.

An example of a layout used to describe the image above is shown below (taken from this sample code):

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33  

Further samples include:

#### Margin Percentages

The margins can also be set to a percentage of the total widths as well:

• app:layout_marginStartPercent
• app:layout_marginEndPercent
• app:layout_marginTopPercent
• app:layout_marginBottomPercent

We can also define app:layout_marginPercent that will be to all four values above.

#### Aspect Ratio

Similar to how [[ImageView|Working-with-the-ImageView#sizing-imageview-controls|]]'s adjustViewBounds:true can be used to scale the image according to its aspect ratio, we can also use PercentRelativeLayout to define an aspect ratio for a layout. If one dimension is set to 0dp and no percent scaling is associated with it, setting a percentage on the app:layout_aspectRatio attribute can scale the other to meet the ratio:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24  

The resulting layout appears as follows:

## FrameLayout

In a frame layout, the children are displayed with a z-index in the order of how they appear. Put simply, the last child added to a FrameLayout will be drawn on top of all the previous children. Think of it like a stack of items, the item last put on the stack will be drawn on top of the items below it. This layout makes it very easy to draw on top of other layouts, especially for tasks such as button placement.

To arrange the children inside of a FrameLayout use the android:layout_gravity attribute along with whatever android:padding and android:margin you need.

Example of FrameLayout snippet:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26  

In this example, an ImageView is set to the full size of the FrameLayout. We then draw two TextView's over it.

## Understanding View Layers

### Layering Introduction

You may notice that when two views overlap on screen, that one view will become hidden behind the other. Views are drawn in layers by default based on the order they appear in the XML. In other words, the view at the bottom of a container is drawn on screen last covering all previously drawn views.

This is described in the official view docs and in the How Android Draws guide with:

The tree is largely recorded and drawn in order, with parents drawn before (i.e., behind) their children, with siblings drawn in the order they appear in the tree. If you set a background drawable for a View, then the View will draw it before calling back to its onDraw() method. The child drawing order can be overridden with custom child drawing order in a ViewGroup, and with setZ(float) custom Z values} set on Views.

In other words, the easiest way to layer is to pay close attention to the order in which the Views are added to your XML file within their container. Lower down in the file means higher up in the Z-axis.

### Elevation

In Android starting from API level 21, items in the layout file get their Z-order both from how they are ordered within the file as well as from their "elevation" with a higher elevation value meaning the item gets a higher Z order. The value of android:elevation must be a dimension value such as 10dp. We can also use the translationZ property to provide the same effect. Read more about elevation here on the official guide.

### Overlapping Two Views

If we want to overlap two views on top of each other, we can do so using either a RelativeLayout or a FrameLayout. Suppose we have two images: a background image and a foreground image and we want to place them on top of one another. The code for this can be achieved with a RelativeLayout such as shown below:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26  

This results in the following:

### Forcing View to the Front

We can force a view to the front of the stack to become visible using:

 1 2 myView.bringToFront(); myView.invalidate(); 

Note: You must be sure to call bringToFront() and invalidate() method on the highest-level view under your root view. See a more detailed example here.

With these methods outlined above, we can easily control the draw order of our views.

## Optimizing Layout Performance

To optimize layout performance, minimize the number of instantiated layouts and especially minimize deep nested layouts whenever possible. This is why you should generally use a RelativeLayout whenever possible instead of nested LinearLayout. A few layout tips are included below:

• Using nested instances of LinearLayout can lead to an excessively deep view hierarchy and can be quite expensive especially expensive as each child needs to be measured twice. This is particularly important when the layout is inflated repeatedly such as in a list.
• Layout performance slows down due to a nested LinearLayout and the performance can be improved by flattening the layout, making the layout shallow and wide rather than narrow and deep. A RelativeLayout as the root node allows for such layouts. So, when this design is converted to use RelativeLayout, the view hierarchy can be flattened significantly.
• Sometimes your layout might require complex views that are rarely used. Whether they are item details, progress indicators, or undo messages, you can reduce memory usage and speed up rendering by loading the views only when they are needed.

Review the following references for more detail on optimizing your view hierarchy:

This is just the beginning. Refer to our [[profiling apps guide|Debugging-and-Profiling-Apps]] for more resources.