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