Android layouts

The first thing to do when you want to create an app for Android using Eclipse is to design a layout, describing how the screen will look like. That was quite easy in my early days with Visual Studio and C++/C#, dragging and dropping forms directly where they should be. The same can be done in Eclipse, using AbsoluteLayout, but this has been “deprecated” (for Google, “deprecated” means you can still use it, the libraries are still there, but no longer supported).

So you have to find your way around the LinearLayout, RelativeLayout, etc etc. These might be enough and straightforward when you have easy UIs to design, but it can be slightly complicated when it comes to UIs like this one.

This can be quite tricky: buttons are not aligned, so using a table is out of the question. But it is not THAT tricky if you are careful in picking which layout comes first. Because the solution lies in embedding layouts, and an understanding of the horizontal or vertical alignment, and the layouts’ respective gravity settings. This example uses only buttons, but you can replace these by any other Android widget you like. The principle is the same.

For instance, here are the layouts used for this particular example:

As you can see, we had to resort to defining multiple layouts. The main layout is obviously the screen layout, which you can see on the right. Given the direction of the overall layout, it just needs to be aligned vertically.
The second layout represents the first “line” of the layout, and is horizontal. You can define the first button directly in it.

However, since we are then trying to pile two buttons vertically (a different alignment from the parent layout!), we need to define a new layout within the layout. Aligning the buttons within the last layout is also something to be weary about. Always try to remember to ask yourself: “what is the parent layout doing?”

Moving to the next “line” of our original layout, the principle is the same: we define a “main” horizontal layout in which we will then embed vertical layouts!

This picture shows how Eclipse represents the outline of the layout; make sure you use this tool as even though it doesn’t help with the positioning of the layouts and widgets, it actually helps a lot when it comes to visualizing the layouts’ hierarchy!

Leave a Reply