Stretching and Spanning layouts in Android

When I was working on my BF2Stats Android app, I had to find out how to place 2 widgets/layout elements on the same horizontal line, while keeping them stretched at the same time so they are filling the width of the screen.

It took me a little research before I found a solution, so I will share two methods with you today.

This tutorial will show you how to create layouts that stretches in the width.

In Eclipse I create a new Android Project by going to File -> New -> Other -> Android -> Android Project. The default project just using the main.xml file for these example layouts will do just fine.

We can create a stretching layout with two different methods; Layout Weights and Layout Spans, I will show a simple example of both, and then I will show how to center an element in a TableLayout with Layout Spans.

Stretching layout using Layout Weights

About Layout Weights

Simply put, layout weights are a way of defining how much of the layout space a widget element will take.

It can be thought of as a percentage of layout space, but it is written 0.2 instead of 20%. So if you want to give an element a size of roughly 20%, you set android:layout_weight=”0.2″ for that element. (These percentages/weights are not exact values, a layout_weight of 0.1 may on your phone turn out to look more like 0.05 or 0.15)

1/5 is 0.2, so the Button should take about 20% of the space, as we can see in the picture below:

How to center an element in a TableLayout

This is another example using Layout Spans and TableLayout. It just demonstrates how you could place elements with the use of the android:layout_span attribute. It also shows how to centre elements in a table, which is very handy.