• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Layouts
2parent.title=User Interface
3parent.link=index.html
4@jd:body
5
6<div id="qv-wrapper">
7<div id="qv">
8  <h2>In this document</h2>
9<ol>
10  <li><a href="#write">Write the XML</a></li>
11  <li><a href="#load">Load the XML Resource</a></li>
12  <li><a href="#attributes">Attributes</a>
13    <ol>
14      <li><a href="#id">ID</a></li>
15      <li><a href="#layout-params">Layout Parameters</a></li>
16    </ol>
17  </li>
18  <li><a href="#Position">Layout Position</a></li>
19  <li><a href="#SizePaddingMargins">Size, Padding and Margins</a></li>
20  <li><a href="#CommonLayouts">Common Layouts</a></li>
21  <li><a href="#AdapterViews">Building Layouts with an Adapter</a>
22    <ol>
23      <li><a href="#FillingTheLayout">Filling an adapter view with data</a></li>
24      <li><a href="#HandlingUserSelections">Handling click events</a></li>
25    </ol>
26  </li>
27</ol>
28
29  <h2>Key classes</h2>
30  <ol>
31    <li>{@link android.view.View}</li>
32    <li>{@link android.view.ViewGroup}</li>
33    <li>{@link android.view.ViewGroup.LayoutParams}</li>
34  </ol>
35</div>
36</div>
37
38<p>Your layout is the architecture for the user interface in an Activity.
39It defines the layout structure and holds all the elements that appear to the user.
40You can declare your layout in two ways:</p>
41<ul>
42<li><strong>Declare UI elements in XML</strong>. Android provides a straightforward XML
43vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.</li>
44<li><strong>Instantiate layout elements at runtime</strong>. Your
45application can create View and ViewGroup objects (and manipulate their properties) programmatically. </li>
46</ul>
47
48<p>The Android framework gives you the flexibility to use either or both of these methods for declaring and managing your application's UI. For example, you could declare your application's default layouts in XML, including the screen elements that will appear in them and their properties. You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time. </p>
49
50<div class="sidebox-wrapper">
51<div class="sidebox">
52  <ul>
53  <li>The <a href="{@docRoot}tools/sdk/eclipse-adt.html">ADT
54  Plugin for Eclipse</a> offers a layout preview of your XML &mdash;
55  with the XML file opened, select the <strong>Layout</strong> tab.</li>
56  <li>You should also try the
57  <a href="{@docRoot}tools/debugging/debugging-ui.html#hierarchyViewer">Hierarchy Viewer</a> tool,
58  for debugging layouts &mdash; it reveals layout property values,
59  draws wireframes with padding/margin indicators, and full rendered views while
60  you debug on the emulator or device.</li>
61  <li>The <a href="{@docRoot}tools/debugging/debugging-ui.html#layoutopt">layoutopt</a> tool lets
62  you quickly analyze your layouts and hierarchies for inefficiencies or other problems.</li>
63</div>
64</div>
65
66<p>The advantage to declaring your UI in XML is that it enables you to better separate the presentation of your application from the code that controls its behavior. Your UI descriptions are external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile. For example, you can create XML layouts for different screen orientations, different device screen sizes, and different languages. Additionally, declaring the layout in XML makes it easier to visualize the structure of your UI, so it's easier to debug problems. As such, this document focuses on teaching you how to declare your layout in XML. If you're
67interested in instantiating View objects at runtime, refer to the {@link android.view.ViewGroup} and
68{@link android.view.View} class references.</p>
69
70<p>In general, the XML vocabulary for declaring UI elements closely follows the structure and naming of the classes and methods, where element names correspond to class names and attribute names correspond to methods. In fact, the correspondence is often so direct that you can guess what XML attribute corresponds to a class method, or guess what class corresponds to a given xml element. However, note that not all vocabulary is identical. In some cases, there are slight naming differences. For
71example, the EditText element has a <code>text</code> attribute that corresponds to
72<code>EditText.setText()</code>. </p>
73
74<p class="note"><strong>Tip:</strong> Learn more about different layout types in <a href="{@docRoot}guide/topics/ui/layout-objects.html">Common
75Layout Objects</a>. There are also a collection of tutorials on building various layouts in the
76<a href="{@docRoot}resources/tutorials/views/index.html">Hello Views</a> tutorial guide.</p>
77
78<h2 id="write">Write the XML</h2>
79
80<div class="sidebox-wrapper">
81<div class="sidebox">
82<p>For your convenience, the API reference documentation for UI related classes
83lists the available XML attributes that correspond to the class methods, including inherited
84attributes.</p>
85<p>To learn more about the available XML elements and attributes, as well as the format of the XML file, see <a
86href="{@docRoot}guide/topics/resources/available-resources.html#layoutresources">Layout Resources</a>.</p>
87</div>
88</div>
89
90<p>Using Android's XML vocabulary, you can quickly design UI layouts and the screen elements they contain, in the same way you create web pages in HTML &mdash; with a series of nested elements. </p>
91
92<p>Each layout file must contain exactly one root element, which must be a View or ViewGroup object. Once you've defined the root element, you can add additional layout objects or widgets as child elements to gradually build a View hierarchy that defines your layout. For example, here's an XML layout that uses a vertical {@link android.widget.LinearLayout}
93to hold a {@link android.widget.TextView} and a {@link android.widget.Button}:</p>
94<pre>
95&lt;?xml version="1.0" encoding="utf-8"?>
96&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
97              android:layout_width="fill_parent"
98              android:layout_height="fill_parent"
99              android:orientation="vertical" >
100    &lt;TextView android:id="@+id/text"
101              android:layout_width="wrap_content"
102              android:layout_height="wrap_content"
103              android:text="Hello, I am a TextView" />
104    &lt;Button android:id="@+id/button"
105            android:layout_width="wrap_content"
106            android:layout_height="wrap_content"
107            android:text="Hello, I am a Button" />
108&lt;/LinearLayout>
109</pre>
110
111<p>After you've declared your layout in XML, save the file with the <code>.xml</code> extension,
112in your Android project's <code>res/layout/</code> directory, so it will properly compile. </p>
113
114<p>We'll discuss each of the attributes shown here a little later.</p>
115
116<h2 id="load">Load the XML Resource</h2>
117
118<p>When you compile your application, each XML layout file is compiled into a
119{@link android.view.View} resource. You should load the layout resource from your application code, in your
120{@link android.app.Activity#onCreate(android.os.Bundle) Activity.onCreate()} callback implementation.
121Do so by calling <code>{@link android.app.Activity#setContentView(int) setContentView()}</code>,
122passing it the reference to your layout resource in the form of:
123<code>R.layout.<em>layout_file_name</em></code>
124For example, if your XML layout is saved as <code>main_layout.xml</code>, you would load it
125for your Activity like so:</p>
126<pre>
127public void onCreate(Bundle savedInstanceState) {
128    super.onCreate(savedInstanceState);
129    setContentView(R.layout.main_layout);
130}
131</pre>
132
133<p>The <code>onCreate()</code> callback method in your Activity is called by the Android framework when
134your Activity is launched (see the discussion about lifecycles, in the
135<a href="{@docRoot}guide/components/activities.html#Lifecycle">Activities</a>
136document).</p>
137
138
139<h2 id="attributes">Attributes</h2>
140
141<p>Every View and ViewGroup object supports their own variety of XML attributes.
142Some attributes are specific to a View object (for example, TextView supports the <code>textSize</code>
143attribute), but these attributes are also inherited by any View objects that may extend this class.
144Some are common to all View objects, because they are inherited from the root View class (like
145the <code>id</code> attribute). And, other attributes are considered "layout parameters," which are
146attributes that describe certain layout orientations of the View object, as defined by that object's
147parent ViewGroup object.</p>
148
149<h3 id="id">ID</h3>
150
151<p>Any View object may have an integer ID associated with it, to uniquely identify the View within the tree.
152When the application is compiled, this ID is referenced as an integer, but the ID is typically
153assigned in the layout XML file as a string, in the <code>id</code> attribute.
154This is an XML attribute common to all View objects
155(defined by the {@link android.view.View} class) and you will use it very often.
156The syntax for an ID, inside an XML tag is:</p>
157<pre>android:id="&#64;+id/my_button"</pre>
158
159<p>The  at-symbol (&#64;) at the beginning of the string indicates that the XML parser should parse and expand the rest
160of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must
161be created and added to our resources (in the <code>R.java</code> file). There are a number of other ID resources that
162are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol,
163but must add the <code>android</code> package namespace, like so:</p>
164<pre>android:id="&#64;android:id/empty"</pre>
165<p>With the <code>android</code> package namespace in place, we're now referencing an ID from the <code>android.R</code>
166resources class, rather than the local resources class.</p>
167
168<p>In order to create views and reference them from the application, a common pattern is to:</p>
169<ol>
170  <li>Define a view/widget in the layout file and assign it a unique ID:
171<pre>
172&lt;Button android:id="&#64;+id/my_button"
173        android:layout_width="wrap_content"
174        android:layout_height="wrap_content"
175        android:text="&#64;string/my_button_text"/>
176</pre>
177  </li>
178  <li>Then create an instance of the view object and capture it from the layout
179(typically in the <code>{@link android.app.Activity#onCreate(Bundle) onCreate()}</code> method):
180<pre>
181Button myButton = (Button) findViewById(R.id.my_button);
182</pre>
183  </li>
184</ol>
185<p>Defining IDs for view objects is important when creating a {@link android.widget.RelativeLayout}.
186In a relative layout, sibling views can define their layout relative to another sibling view,
187which is referenced by the unique ID.</p>
188<p>An ID need not be unique throughout the entire tree, but it should be
189unique within the part of the tree you are searching (which may often be the entire tree, so it's best
190to be completely unique when possible).</p>
191
192
193<h3 id="layout-params">Layout Parameters</h3>
194
195<p>XML layout attributes named <code>layout_<em>something</em></code> define
196layout parameters for the View that are appropriate for the ViewGroup in which it resides.</p>
197
198<p>Every ViewGroup class implements a nested class that extends {@link
199android.view.ViewGroup.LayoutParams}. This subclass
200contains property types that define the size and position for each child view, as
201appropriate for the view group. As you can see in figure 1, the parent
202view group defines layout parameters for each child view (including the child view group).</p>
203
204<img src="{@docRoot}images/layoutparams.png" alt="" />
205<p class="img-caption"><strong>Figure 1.</strong> Visualization of a view hierarchy with layout
206parameters associated with each view.</p>
207
208<p>Note that every LayoutParams subclass has its own syntax for setting
209values. Each child element must define LayoutParams that are appropriate for its parent,
210though it may also define different LayoutParams for its own children. </p>
211
212<p>All view groups include a width and height (<code>layout_width</code> and
213<code>layout_height</code>), and each view is required to define them. Many
214LayoutParams also include optional margins and borders. <p>
215
216<p>You can specify width and height with exact measurements, though you probably
217won't want to do this often. More often, you will use one of these constants to
218set the width or height: </p>
219
220<ul>
221  <li><var>wrap_content</var> tells your view to size itself to the dimensions
222required by its content</li>
223  <li><var>fill_parent</var> (renamed <var>match_parent</var> in API Level 8)
224tells your view to become as big as its parent view group will allow.</li>
225</ul>
226
227<p>In general, specifying a layout width and height using absolute units such as
228pixels is not recommended. Instead, using relative measurements such as
229density-independent pixel units (<var>dp</var>), <var>wrap_content</var>, or
230<var>fill_parent</var>, is a better approach, because it helps ensure that
231your application will display properly across a variety of device screen sizes.
232The accepted measurement types are defined in the
233<a href="{@docRoot}guide/topics/resources/available-resources.html#dimension">
234Available Resources</a> document.</p>
235
236
237<h2 id="Position">Layout Position</h2>
238   <p>
239   The geometry of a view is that of a rectangle. A view has a location,
240   expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
241   two dimensions, expressed as a width and a height. The unit for location
242   and dimensions is the pixel.
243   </p>
244
245   <p>
246   It is possible to retrieve the location of a view by invoking the methods
247   {@link android.view.View#getLeft()} and {@link android.view.View#getTop()}. The former returns the left, or X,
248   coordinate of the rectangle representing the view. The latter returns the
249   top, or Y, coordinate of the rectangle representing the view. These methods
250   both return the location of the view relative to its parent. For instance,
251   when getLeft() returns 20, that means the view is located 20 pixels to the
252   right of the left edge of its direct parent.
253   </p>
254
255   <p>
256   In addition, several convenience methods are offered to avoid unnecessary
257   computations, namely {@link android.view.View#getRight()} and {@link android.view.View#getBottom()}.
258   These methods return the coordinates of the right and bottom edges of the
259   rectangle representing the view. For instance, calling {@link android.view.View#getRight()}
260   is similar to the following computation: <code>getLeft() + getWidth()</code>.
261   </p>
262
263
264<h2 id="SizePaddingMargins">Size, Padding and Margins</h2>
265   <p>
266   The size of a view is expressed with a width and a height. A view actually
267   possess two pairs of width and height values.
268   </p>
269
270   <p>
271   The first pair is known as <em>measured width</em> and
272   <em>measured height</em>. These dimensions define how big a view wants to be
273   within its parent. The
274   measured dimensions can be obtained by calling {@link android.view.View#getMeasuredWidth()}
275   and {@link android.view.View#getMeasuredHeight()}.
276   </p>
277
278   <p>
279   The second pair is simply known as <em>width</em> and <em>height</em>, or
280   sometimes <em>drawing width</em> and <em>drawing height</em>. These
281   dimensions define the actual size of the view on screen, at drawing time and
282   after layout. These values may, but do not have to, be different from the
283   measured width and height. The width and height can be obtained by calling
284   {@link android.view.View#getWidth()} and {@link android.view.View#getHeight()}.
285   </p>
286
287   <p>
288   To measure its dimensions, a view takes into account its padding. The padding
289   is expressed in pixels for the left, top, right and bottom parts of the view.
290   Padding can be used to offset the content of the view by a specific amount of
291   pixels. For instance, a left padding of 2 will push the view's content by
292   2 pixels to the right of the left edge. Padding can be set using the
293   {@link android.view.View#setPadding(int, int, int, int)} method and queried by calling
294   {@link android.view.View#getPaddingLeft()}, {@link android.view.View#getPaddingTop()},
295   {@link android.view.View#getPaddingRight()} and {@link android.view.View#getPaddingBottom()}.
296   </p>
297
298   <p>
299   Even though a view can define a padding, it does not provide any support for
300   margins. However, view groups provide such a support. Refer to
301   {@link android.view.ViewGroup} and
302   {@link android.view.ViewGroup.MarginLayoutParams} for further information.
303   </p>
304
305   <p>For more information about dimensions, see
306   <a href="{@docRoot}guide/topics/resources/more-resources.html#Dimension">Dimension Values</a>.
307   </p>
308
309
310
311
312
313
314<style type="text/css">
315div.layout {
316  float:left;
317  width:200px;
318  margin:0 0 20px 20px;
319}
320div.layout.first {
321  margin-left:0;
322  clear:left;
323}
324</style>
325
326
327
328
329<h2 id="CommonLayouts">Common Layouts</h2>
330
331<p>Each subclass of the {@link android.view.ViewGroup} class provides a unique way to display
332the views you nest within it. Below are some of the more common layout types that are built
333into the Android platform.</p>
334
335<p class="note"><strong>Note:</strong> Although you can nest one or more layouts within another
336layout to acheive your UI design, you should strive to keep your layout hierarchy as shallow as
337possible. Your layout draws faster if it has fewer nested layouts (a wide view hierarchy is
338better than a deep view hierarchy).</p>
339
340<!--
341<h2 id="framelayout">FrameLayout</h2>
342<p>{@link android.widget.FrameLayout FrameLayout} is the simplest type of layout
343object. It's basically a blank space on your screen that you can
344later fill with a single object &mdash; for example, a picture that you'll swap in and out.
345All child elements of the FrameLayout are pinned to the top left corner of the screen; you cannot
346specify a different location for a child view. Subsequent child views will simply be drawn over
347previous ones,
348partially or totally obscuring them (unless the newer object is transparent).
349</p>
350-->
351
352
353<div class="layout first">
354  <h4><a href="layout/linear.html">Linear Layout</a></h4>
355  <a href="layout/linear.html"><img src="{@docRoot}images/ui/linearlayout-small.png" alt="" /></a>
356  <p>A layout that organizes its children into a single horizontal or vertical row. It
357  creates a scrollbar if the length of the window exceeds the length of the screen.</p>
358</div>
359
360<div class="layout">
361  <h4><a href="layout/relative.html">Relative Layout</a></h4>
362  <a href="layout/relative.html"><img src="{@docRoot}images/ui/relativelayout-small.png" alt=""
363/></a>
364  <p>Enables you to specify the location of child objects relative to each other (child A to
365the left of child B) or to the parent (aligned to the top of the parent).</p>
366</div>
367
368<!--
369<div class="layout">
370  <h4><a href="layout/tabs.html">Tabs</a></h4>
371  <a href="layout/tabs.html"><img src="{@docRoot}images/ui/tabs-small.png" alt="" /></a>
372  <p>Provides a tab selection list that monitors clicks and enables the application to change
373the screen whenever a tab is clicked.</p>
374</div>
375
376<div class="layout first">
377  <h4><a href="layout/grid.html">Table Layout</a></h4>
378  <a href="layout/table.html"><img src="{@docRoot}images/ui/gridlayout-small.png" alt="" /></a>
379  <p>A tabular layout with an arbitrary number of rows and columns, each cell holding the
380widget of your choice. The rows resize to fit the largest column. The cell borders are not
381visible.</p>
382</div>
383-->
384
385<div class="layout">
386  <h4><a href="{@docRoot}guide/webapps/webview.html">Web View</a></h4>
387  <a href="{@docRoot}guide/webapps/webview.html"><img src="{@docRoot}images/ui/webview-small.png"
388alt="" /></a>
389  <p>Displays web pages.</p>
390</div>
391
392
393
394
395<h2 id="AdapterViews" style="clear:left">Building Layouts with an Adapter</h2>
396
397<p>When the content for your layout is dynamic or not pre-determined, you can use a layout that
398subclasses {@link android.widget.AdapterView} to populate the layout with views at runtime. A
399subclass of the {@link android.widget.AdapterView} class uses an {@link android.widget.Adapter} to
400bind data to its layout. The {@link android.widget.Adapter} behaves as a middle-man between the data
401source and the {@link android.widget.AdapterView} layout&mdash;the {@link android.widget.Adapter}
402retreives the data (from a source such as an array or a database query) and converts each entry
403into a view that can be added into the {@link android.widget.AdapterView} layout.</p>
404
405<p>Common layouts backed by an adapter include:</p>
406
407<div class="layout first">
408  <h4><a href="layout/listview.html">List View</a></h4>
409  <a href="layout/list.html"><img src="{@docRoot}images/ui/listview-small.png" alt="" /></a>
410  <p>Displays a scrolling single column list.</p>
411</div>
412
413<div class="layout">
414  <h4><a href="layout/gridview.html">Grid View</a></h4>
415  <a href="layout/grid.html"><img src="{@docRoot}images/ui/gridview-small.png" alt="" /></a>
416  <p>Displays a scrolling grid of columns and rows.</p>
417</div>
418
419
420
421<h3 id="FillingTheLayout" style="clear:left">Filling an adapter view with data</h3>
422
423<p>You can populate an {@link android.widget.AdapterView} such as {@link android.widget.ListView} or
424{@link android.widget.GridView} by binding the {@link android.widget.AdapterView} instance to an
425{@link android.widget.Adapter}, which retrieves data from an external source and creates a {@link
426android.view.View} that represents each data entry.</p>
427
428<p>Android provides several subclasses of {@link android.widget.Adapter} that are useful for
429retrieving different kinds of data and building views for an {@link android.widget.AdapterView}. The
430two most common adapters are:</p>
431
432<dl>
433  <dt>{@link android.widget.ArrayAdapter}</dt>
434    <dd>Use this adapter when your data source is an array. By default, {@link
435android.widget.ArrayAdapter} creates a view for each array item by calling {@link
436java.lang.Object#toString()} on each item and placing the contents in a {@link
437android.widget.TextView}.
438      <p>For example, if you have an array of strings you want to display in a {@link
439android.widget.ListView}, initialize a new {@link android.widget.ArrayAdapter} using a
440constructor to specify the layout for each string and the string array:</p>
441<pre>
442ArrayAdapter adapter = new ArrayAdapter&lt;String>(this,
443        android.R.layout.simple_list_item_1, myStringArray);
444</pre>
445<p>The arguments for this constructor are:</p>
446<ul>
447  <li>Your app {@link android.content.Context}</li>
448  <li>The layout that contains a {@link android.widget.TextView} for each string in the array</li>
449  <li>The string array</li>
450</ul>
451<p>Then simply call
452{@link android.widget.ListView#setAdapter setAdapter()} on your {@link android.widget.ListView}:</p>
453<pre>
454ListView listView = (ListView) findViewById(R.id.listview);
455listView.setAdapter(adapter);
456</pre>
457
458      <p>To customize the appearance of each item you can override the {@link
459java.lang.Object#toString()} method for the objects in your array. Or, to create a view for each
460item that's something other than a {@link android.widget.TextView} (for example, if you want an
461{@link android.widget.ImageView} for each array item), extend the {@link
462android.widget.ArrayAdapter} class and override {@link android.widget.ArrayAdapter#getView
463getView()} to return the type of view you want for each item.</p>
464
465</dd>
466
467  <dt>{@link android.widget.SimpleCursorAdapter}</dt>
468    <dd>Use this adapter when your data comes from a {@link android.database.Cursor}. When
469using {@link android.widget.SimpleCursorAdapter}, you must specify a layout to use for each
470row in the {@link android.database.Cursor} and which columns in the {@link android.database.Cursor}
471should be inserted into which views of the layout. For example, if you want to create a list of
472people's names and phone numbers, you can perform a query that returns a {@link
473android.database.Cursor} containing a row for each person and columns for the names and
474numbers. You then create a string array specifying which columns from the {@link
475android.database.Cursor} you want in the layout for each result and an integer array specifying the
476corresponding views that each column should be placed:</p>
477<pre>
478String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME,
479                        ContactsContract.CommonDataKinds.Phone.NUMBER};
480int[] toViews = {R.id.display_name, R.id.phone_number};
481</pre>
482<p>When you instantiate the {@link android.widget.SimpleCursorAdapter}, pass the layout to use for
483each result, the {@link android.database.Cursor} containing the results, and these two arrays:</p>
484<pre>
485SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
486        R.layout.person_name_and_number, cursor, fromColumns, toViews, 0);
487ListView listView = getListView();
488listView.setAdapter(adapter);
489</pre>
490<p>The {@link android.widget.SimpleCursorAdapter} then creates a view for each row in the
491{@link android.database.Cursor} using the provided layout by inserting each {@code
492fromColumns} item into the corresponding {@code toViews} view.</p>.</dd>
493</dl>
494
495
496<p>If, during the course of your application's life, you change the underlying data that is read by
497your adapter, you should call {@link android.widget.ArrayAdapter#notifyDataSetChanged()}. This will
498notify the attached view that the data has been changed and it should refresh itself.</p>
499
500
501
502<h3 id="HandlingUserSelections">Handling click events</h3>
503
504<p>You can respond to click events on each item in an {@link android.widget.AdapterView} by
505implementing the {@link android.widget.AdapterView.OnItemClickListener} interface. For example:</p>
506
507<pre>
508// Create a message handling object as an anonymous class.
509private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
510    public void onItemClick(AdapterView parent, View v, int position, long id) {
511        // Do something in response to the click
512    }
513};
514
515listView.setOnItemClickListener(mMessageClickedHandler);
516</pre>
517
518
519
520