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:
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:
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.
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).
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 [email protected], via their blog at androidbook.blogspot.com, and on Twitter @androidwireless.
Comments