Android User Interface Design: Layout Basics

Android User Interface Design: Layout Basics

Tutorial Details
  • Estimated Completion Time: 45 Minutes
  • Technology: Eclipse + Android SDK
  • Difficulty: Beginner
This entry is part 1 of 21 in the series Android User Interface Design

Understanding layouts is important for good Android application design. In this tutorial, we provide an overview of how layouts fit into the Android application architecture. We also explore some of the specific layout controls available for organizing application screen content in a variety of interesting ways.

What Is A Layout?

Android developers use the term layout to mean one of two things. Both definitions apply to this tutorial, and are, unfortunately used interchangeably in the Android development community. The two definitions of layout are:

  • A type of resource that defines what is drawn on the screen. Layout resources are stored as XML files in the /res/layout resource directory for the application. A layout resource is simply a template for a user interface screen, or portion of a screen, and contain.
  • A type of View class whose primary purpose is to organize other controls. These layout classes (LinearLayout, RelativeLayout, TableLayout, etc. ) are used to display child controls, such as text controls or buttons or images on the screen.

Android user interfaces can be defined as layout resources in XML or created programmatically.

Using Eclipse to Design Layout Resources

The Android Development Plug-in for Eclipse includes a handy layout resource designer for designing and previewing layout resources. The tool includes two tab views: the Layout view allows you to preview how the controls will appear on various screens and for each orientation and the XML view shows you the XML definition of the resource. The layout resource designer is shown in this figure:

Layout figure 1

Here are some tips for working with the layout resource designer in Eclipse:

  • Use the Outline pane to Add and Remove controls to your layout resource.
  • Select a specific control (either in the Preview or the Outline) and use the Property pane to adjust a specific control’s attributes.
  • Use the XML tab to edit the XML definition directly.

It’s important to remember that the Eclipse layout resource designer preview can’t replicate exactly how the layout will appear to end users. For this, you must test your application on a properly configured emulator and, more importantly, on your target devices. Also, certain “complex” controls, including tabs or video viewers, cannot be previewed within Eclipse.

Defining an XML Layout Resource

The most convenient and maintainable way to design application user interfaces is by creating XML layout resources. This method greatly simplifies the UI design process, moving much of the static creation and layout of user interface controls and definition of control attributes, to the XML, instead of littering the code. It creates a potential distinction between UI designers (who concern themselves more with layout) and developers (who know Java and implement application functionality). Developers can still alter the content of a screen programmatically when necessary. Complex controls, like ListView or GridView, are usually populated with data programmatically.

XML layout resources must be stored in the /res/layout project directory (or, in the case of alternative resources, in a specially named sub-directory). It’s common practice to create an XML layout resource for each screen in your application (closely tied to a specific Activity), but this is not required. You could, in theory, create an XML layout resource and use it for different activities, supplying different data on the screen. You can also componentized your layout resources and include them within one another, if needed.

The following is a simple XML layout resource, a template with a LinearLayout containing a TextView and an ImageView, defined in XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center">
    <TextView
        android:layout_width="fill_parent"
        android:id="@+id/PhotoLabel"
        android:layout_height="wrap_content"
        android:text="@string/my_text_label"
        android:gravity="center_horizontal"
        android:textSize="20dp" />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/matterhorn"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"
        android:maxHeight="250dp"
        android:maxWidth="250dp"
        android:id="@+id/Photo" />
</LinearLayout>

This layout represents a simple screen with two controls: first some text and then an image below it. These controls are organized within a vertically oriented LinearLayout. The following two figures show what this layout might look like on a device in both portrait and landscape modes:

Layout figure 2
Layout figure 2b

Within the Activity, only a single line of code within the onCreate() method is necessary to load and display a layout resource on the screen. If the layout resource was stored in the /res/layout/main.xml file, that would be:

setContentView(R.layout.main);

Defining a Layout Programmatically

You can also programmatically create user interface components. For organization and maintainability, this is best left for the odd case rather than the norm. Instead of loading a layout resource directly using the setContentView() method, you must instead build up the screen contents and then supply a parent layout object which contains all the control contents to display as child views to the setContentView() method.

For example, the following code illustrates how to programmatically have an Activity instantiate a LinearLayout view and place two TextView objects within it. No resources whatsoever are used.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.main);
    TextView label = new TextView(this);
    label.setText(R.string.my_text_label);
    label.setTextSize(20);
    label.setGravity(Gravity.CENTER_HORIZONTAL);
    ImageView pic = new ImageView(this);
    pic.setImageResource(R.drawable.matterhorn);
    pic.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    pic.setAdjustViewBounds(true);
    pic.setScaleType(ScaleType.FIT_XY);
    pic.setMaxHeight(250);
    pic.setMaxWidth(250);
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    ll.setGravity(Gravity.CENTER);
    ll.addView(label);
    ll.addView(pic);
    setContentView(ll);
}

As you can see, the code can rapidly grow in size as more controls are added to the screen, making screen contents more difficult to maintain or reuse.

Exploring Various Layout Types

Now let’s turn our attention to those helpful layout controls that organize other controls. The most commonly used layout classes are:

  • FrameLayout – designed to display a stack of child View controls. Multiple view controls can be added to this layout. This can be used to show multiple controls within the same screen space.
  • LinearLayout – designed to display child View controls in a single row or column. This is a very handy layout method for creating forms.
  • RelativeLayout – designed to display child View controls in relation to each other. For instance, you can set a control to be positioned “above” or “below” or “to the left of” or “to the right of” another control, referred to by its unique identifier. You can also align child View controls relative to the parent edges.
  • TableLayout – designed to organize child View controls into rows and columns. Individual View controls are added within each row of the table using a TableRow layout View (which is basically a horizontally oriented LinearLayout) for each row of the table.
Layout figure 3
Layout figure 3b
Layout figure 3c
Layout figure 3d

Combining Layouts To Organize Controls

A layout (LinearLayout, TableLayout, RelativeLayout, etc.) is a control like any other. This means that layout controls can be nested. For example, you might use a RelativeLayout within a LinearLayout, or vice-versa, in order to organize controls on a screen. The following figure shows a screen with a LinearLayout (parent), a TableLayout (top child)_and a FrameLayout (bottom child).

Layout figure 4

But beware! Keep your screens relatively simple; complex layouts load slowly and cause performance issues.

Providing Alternative Layout Resources

Consider device differences when designing your application layout resources. It is often possible to design flexible layouts that look fine on a variety of different devices, in both portrait and landscape modes. When necessary, you can include alternative layout resources to handle special cases. For example, you could provide different layouts to load depending upon the orientation of the device or whether or not the device has a large screen (e.g. an internet tablet).

For more information on how to use alternative resources, see the Android SDK documentation on Android Resources.

Layout Tools and Optimization

The Android SDK includes several tools that can help design, debug and optimize layout resources. In addition to the layout resource designer built into the Android plug-in for Eclipse, you can use the Hierarchy Viewer and layoutopt tools provided with the Android SDK. These tools are available in the /tools directory of your Android SDK.

You can use the Hierarchy Viewer to inspect layout details at run-time. Find out more about the Hierarchy Viewer on the Android Developer website.

You can use the layoutopt command-line tool to optimize your layout files. Optimizing layouts is important because complicated layout files are slow to load. The layoutopt tool simply scans XML layout files and identifies unnecessary controls. Find out more about the layoutopt tool on the Android Developer website.

Conclusion

Android application user interfaces are defined using layouts. There are a number of different types of layout types that can be used to organize controls on a screen, or portion of a screen. Layouts can be defined using XML resources, or programmatically at run-time in Java. Alternative layouts can be loaded under special circumstances, such as to provide an alternative user interface in portrait versus landscape mode. Finally, designing good layouts is important for application performance; use Android SDK tools like the Hierarchy Viewer and layoutopt to debug and optimize your application layouts.

About the Authors

Mobile developers Lauren Darcey and Shane Conder have coauthored several books on Android development: an in-depth programming book entitled Android Wireless Application Development and Sams TeachYourself Android Application Development in 24 Hours. When not writing, they spend their time developing mobile software at their company and providing consulting services. They can be reached at via email to androidwirelessdev+mt@gmail.com, via their blog at androidbook.blogspot.com, and on Twitter @androidwireless.

Need More Help Writing Android Apps? Check out our Latest Books and Resources!

Buy Android Wireless Application Development, 2nd Edition  Buy Sam's Teach Yourself Android Application Development in 24 Hours  Mamlambo code at Code Canyon

Series NavigationAndroid User Interface Design: Basic Buttons»

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Massimo Nastasi

    Very user tutorial.thank you

  • http://www.techwench.com neo

    im the user of android o.s. phone thanks for this tutorial

  • Mike

    Nice tutorial.. much thanks.

  • http://designgalleries.yolasite.com/ Florin Safner

    Hello. I was designing this layout UI for a client but I used Photoshop and this allows me to add a lot of nice ellements in the UI and the vector shapes.
    He does not have the right background dimmensions and resolution, which is all I need.
    He sent to me a capture which size is:
    Width: 1,663 inch
    Height: 2,22 inch
    Resolution: 300 pixels/inch

    Does anyone here know if this is right or do you have the real sizes and resolution?
    Thank you

  • Tired

    I just updated my Android SDK/etc (Eclipse IDE) and, while there seems to be some nice, new aspects/features of the Graphical Layout part for xml’s, the previous ability of moving items using the Red Arrows up/down is missing and I’m not able to move items around (in or out of layouts).

    Am I missing something? Thanks

  • Manoj

    I am trying to place a TextView or button in the middle of the screen, but it does not stay there. It goes to the upper corner always. How can we place the controls anywhere freely?

    • Igor G.

      Have you tried the Graphical Layout, where you can right-click on a component and set its placement.

  • Charlie

    Why i try run sourcecode then not show image Y_Y

    • http://dev.saddacrackers.com John Cardwell

      You have to add an image with the same name from the “pic.setImageResource(R.drawable.matterhorn); ” line to your res/drawable folders.

  • http://www.praveenmodi.com Praveen

    Thank you! Cool stuff.

  • lilian

    nice tutorial ….. i like it.. more plssss!!!

  • Sharab

    thanks for posting… Really it is usefull stuff..

  • Jun

    Thank you for your tutorial, very useful

  • http://www.rolustech.com/ Ammad Arshad

    I see in every blog there are alot of useful tutorial which explain the android basics but their is a porblem.who ever post the toturial should define with complete example from scratch to well defined application …then it may be more usefull fo beginners.

  • Weberte

    Thanks, it’s very useful.

  • welington dias

    could you give me an example using the database for the login context. How to validate user login now booting the Walloons of the fields directly from the database. I developed the code but does not validate the login, the code for my logic is correct. Thank you for your attention.This is the code I’m using:
    Obs: I have what I call a method to position the cursor before the first registro.Isso he’s doing well.

    public void verificaUsuario(String usuario,String senha)
    {

    try
    {

    usuario = cursor.getString(cursor.getColumnIndex(“usuario”));
    senha = cursor.getString(cursor.getColumnIndex(“senha”));

    String nomeUsuario = etUsuario.getText().toString();
    String nomeSenha = etSenha.getText().toString();

    if(usuario.equals(nomeUsuario) && senha.equals(nomeSenha))
    {
    chamaTelaPrincipal();
    cursor.close();
    fechaBanco();
    }

    else
    cursor.close();
    exibirMensagem(“Erro ao Entrar no Sistema PDV!”,”Senha ou Usuario Incorretos!”);

    }catch(Exception erro)
    {
    cursor.close();
    exibirMensagem(“Verificação de Usuario!”,”Houve um pequeno problema na verificação!”+ erro.getMessage());

    }

    }

  • http://zone-android.fr Zone-Android

    Excellent tutorial i was able to grasp the main concept. I use the WYSIWYG editor of Android SDK in Eclipse, works like a charm :)

  • Penguin

    In Eclipse graphical layout, there is a button to ‘Add row ‘ to a table layout but not a button to ‘add column’ that means you cant add columns to a table layout.
    I need to concentrate on my application, not spend weeks and weeks and weeks tying to find a simple way to add a column to a table.
    I think eclipse is a bulky useless nightmare.

    • Alexis

      In Eclipse graphical layout, there is a button to ‘Add row ‘ to a table layout but not a button to ‘add column’ that means you cant add columns to a table layout.

      This is because the TableLayout is not the GridLayout that appeared in Android 4.0. Each line of the TableLayout is an independant cell.

  • r3d

    superr…