declaring-layout.jd revision b7e7b710654b0a99fb8c41a7c47fe6b0f48f6db9
1page.title=Declaring Layout
2parent.title=User Interface
3parent.link=index.html
4@jd:body
5
6<div id="qv-wrapper">
7<div id="qv">
8  <h2>Key classes</h2>
9  <ol>
10    <li>{@link android.view.View}</li>
11    <li>{@link android.view.ViewGroup}</li>
12    <li>{@link android.view.ViewGroup.LayoutParams}</li>
13  </ol>
14  <h2>In this document</h2>
15  <ol>
16    <li><a href="#write">Write the XML</a></li>
17    <li><a href="#load">Load the XML Resource</a></li>
18    <li><a href="#attributes">Attributes</a>
19      <ol>
20        <li><a href="#id">ID</a></li>
21        <li><a href="#layout-params">Layout Parameters</a></li>
22      </ol>
23    </li>
24    <li><a href="#Position">Position</a></li>
25    <li><a href="#SizePaddingMargin">Size, Padding and Margins</a></li>
26    <li><a href="#example">Example Layout</a></li>
27  </ol>
28
29</div>
30</div>
31
32<p>Your layout is the architecture for the user interface in an Activity.
33It defines the layout structure and holds all the elements that appear to the user. 
34You can declare your layout in two ways:</p>
35<ul>
36<li><strong>Declare UI elements in XML</strong>. Android provides a straightforward XML 
37vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.</li>
38<li><strong>Instantiate layout elements at runtime</strong>. Your 
39application can create View and ViewGroup objects (and manipulate their properties) programmatically. </li>
40</ul>
41
42<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>
43
44<div class="sidebox">
45  <ul>
46  <li>The <a href="{@docRoot}sdk/eclipse-adt.html">ADT
47  Plugin for Eclipse</a> offers a layout preview of your XML &mdash; 
48  with the XML file opened, select the <strong>Layout</strong> tab.</li>
49  <li>You should also try the 
50  <a href="{@docRoot}guide/developing/tools/hierarchy-viewer.html">Hierarchy Viewer</a> tool, 
51  for debugging layouts &mdash; it reveals layout property values, 
52  draws wireframes with padding/margin indicators, and full rendered views while 
53  you debug on the emulator or device.</li>
54  <li>The <a href="{@docRoot}guide/developing/tools/layoutopt.html">layoutopt</a> tool lets
55  you quickly analyze your layouts and hierarchies for inefficiencies or other problems.</li>
56</div>
57
58<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
59interested in instantiating View objects at runtime, refer to the {@link android.view.ViewGroup} and 
60{@link android.view.View} class references.</p>
61
62<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
63example, the EditText element has a <code>text</code> attribute that corresponds to
64<code>EditText.setText()</code>. </p>
65
66<p class="note"><strong>Tip:</strong> Learn more about different layout types in <a href="{@docRoot}guide/topics/ui/layout-objects.html">Common
67Layout Objects</a>. There are also a collection of tutorials on building various layouts in the
68<a href="{@docRoot}guide/tutorials/views/index.html">Hello Views</a> tutorial guide.</p>
69
70<h2 id="write">Write the XML</h2>
71
72<div class="sidebox"><p>For your convenience, the API reference documentation for UI related classes lists the available XML attributes that correspond to the class methods, including inherited attributes.</p>
73<p>To learn more about the available XML elements and attributes, as well as the format of the XML file, see <a
74href="{@docRoot}guide/topics/resources/available-resources.html#layoutresources">Layout Resources</a>.</p>
75 </div>
76
77<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>
78
79<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}
80to hold a {@link android.widget.TextView} and a {@link android.widget.Button}:</p>
81<pre>
82&lt;?xml version="1.0" encoding="utf-8"?>
83&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
84              android:layout_width="fill_parent" 
85              android:layout_height="fill_parent" 
86              android:orientation="vertical" >
87    &lt;TextView android:id="@+id/text"
88              android:layout_width="wrap_content"
89              android:layout_height="wrap_content"
90              android:text="Hello, I am a TextView" />
91    &lt;Button android:id="@+id/button"
92            android:layout_width="wrap_content"
93            android:layout_height="wrap_content"
94            android:text="Hello, I am a Button" />
95&lt;/LinearLayout>
96</pre>
97
98<p>After you've declared your layout in XML, save the file with the <code>.xml</code> extension, 
99in your Android project's <code>res/layout/</code> directory, so it will properly compile. </p>
100
101<p>We'll discuss each of the attributes shown here a little later.</p>
102
103<h2 id="load">Load the XML Resource</h2>
104
105<p>When you compile your application, each XML layout file is compiled into a
106{@link android.view.View} resource. You should load the layout resource from your application code, in your 
107{@link android.app.Activity#onCreate(android.os.Bundle) Activity.onCreate()} callback implementation.
108Do so by calling <code>{@link android.app.Activity#setContentView(int) setContentView()}</code>, 
109passing it the reference to your layout resource in the form of: 
110<code>R.layout.<em>layout_file_name</em></code>  
111For example, if your XML layout is saved as <code>main_layout.xml</code>, you would load it
112for your Activity like so:</p>
113<pre>
114public void onCreate(Bundle savedInstanceState) {
115    super.onCreate(savedInstanceState);
116    setContentView.(R.layout.main_layout);
117}
118</pre>
119
120<p>The <code>onCreate()</code> callback method in your Activity is called by the Android framework when
121your Activity is launched (see the discussion on Lifecycles, in the 
122<a href="{@docRoot}guide/topics/fundamentals.html#lcycles">Application Fundamentals</a>, for more on this).</p>
123
124
125<h2 id="attributes">Attributes</h2>
126
127<p>Every View and ViewGroup object supports their own variety of XML attributes.
128Some attributes are specific to a View object (for example, TextView supports the <code>textSize</code>
129attribute), but these attributes are also inherited by any View objects that may extend this class.
130Some are common to all View objects, because they are inherited from the root View class (like 
131the <code>id</code> attribute). And, other attributes are considered "layout parameters," which are 
132attributes that describe certain layout orientations of the View object, as defined by that object's
133parent ViewGroup object.</p>
134
135<h3 id="id">ID</h3>
136
137<p>Any View object may have an integer ID associated with it, to uniquely identify the View within the tree.
138When the application is compiled, this ID is referenced as an integer, but the ID is typically 
139assigned in the layout XML file as a string, in the <code>id</code> attribute.
140This is an XML attribute common to all View objects
141(defined by the {@link android.view.View} class) and you will use it very often. 
142The syntax for an ID, inside an XML tag is:</p>
143<pre>android:id="&#64;+id/my_button"</pre>
144
145<p>The  at-symbol (&#64;) at the beginning of the string indicates that the XML parser should parse and expand the rest
146of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must
147be created and added to our resources (in the <code>R.java</code> file). There are a number of other ID resources that
148are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol,
149but must add the <code>android</code> package namespace, like so:</p>
150<pre>android:id="&#64;android:id/empty"</pre>
151<p>With the <code>android</code> package namespace in place, we're now referencing an ID from the <code>android.R</code>
152resources class, rather than the local resources class.</p>
153
154<p>In order to create views and reference them from the application, a common pattern is to:</p>
155<ol>
156  <li>Define a view/widget in the layout file and assign it a unique ID:
157<pre>
158&lt;Button android:id="&#64;+id/my_button"
159        android:layout_width="wrap_content"
160        android:layout_height="wrap_content"
161        android:text="&#64;string/my_button_text"/>
162</pre>
163  </li>
164  <li>Then create an instance of the view object and capture it from the layout 
165(typically in the <code>{@link android.app.Activity#onCreate(Bundle) onCreate()}</code> method):
166<pre>
167Button myButton = (Button) findViewById(R.id.my_button);
168</pre>
169  </li>
170</ol>
171<p>Defining IDs for view objects is important when creating a {@link android.widget.RelativeLayout}.
172In a relative layout, sibling views can define their layout relative to another sibling view, 
173which is referenced by the unique ID.</p>
174<p>An ID need not be unique throughout the entire tree, but it should be
175unique within the part of the tree you are searching (which may often be the entire tree, so it's best 
176to be completely unique when possible).</p>
177
178
179<h3 id="layout-params">Layout Parameters</h3>
180
181<p>XML layout attributes named <code>layout_<em>something</em></code> define 
182layout parameters for the View that are appropriate for the ViewGroup in which it resides.</p>
183
184<p>Every ViewGroup class implements a nested class that extends {@link
185android.view.ViewGroup.LayoutParams}. This subclass
186contains property types that define the size and position for each child view, as
187appropriate for the view group. As you can see in the figure below, the parent
188view group defines layout parameters for each child view (including the child view group).</p>
189
190<img src="{@docRoot}images/layoutparams.png" alt="" height="300" align="center"/>
191
192<p>Note that every LayoutParams subclass has its own syntax for setting
193values. Each child element must define LayoutParams that are appropriate for its parent, 
194though it may also define different LayoutParams for its own children. </p>
195
196<p>All view groups include a width and height (<code>layout_width</code> and <code>layout_height</code>), 
197and each view is required to define them. 
198Many LayoutParams also include optional margins and
199borders. You can specify width and height with exact measurements, though you probably won't want
200to do this often. More often, you will tell your view to size itself either to
201the dimensions required by its content, or to become as big as its parent view group
202will allow (with the <var>wrap_content</var> and <var>fill_parent</var> values, respectively).
203The accepted measurement types are defined in the 
204<a href="{@docRoot}guide/topics/resources/available-resources.html#dimension">Available Resources</a> document.</p>
205
206
207<h2 id="Position">Layout Position</h2>
208   <p>
209   The geometry of a view is that of a rectangle. A view has a location,
210   expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
211   two dimensions, expressed as a width and a height. The unit for location
212   and dimensions is the pixel.
213   </p>
214  
215   <p>
216   It is possible to retrieve the location of a view by invoking the methods
217   {@link android.view.View#getLeft()} and {@link android.view.View#getTop()}. The former returns the left, or X,
218   coordinate of the rectangle representing the view. The latter returns the
219   top, or Y, coordinate of the rectangle representing the view. These methods
220   both return the location of the view relative to its parent. For instance,
221   when getLeft() returns 20, that means the view is located 20 pixels to the
222   right of the left edge of its direct parent.
223   </p>
224  
225   <p>
226   In addition, several convenience methods are offered to avoid unnecessary
227   computations, namely {@link android.view.View#getRight()} and {@link android.view.View#getBottom()}.
228   These methods return the coordinates of the right and bottom edges of the
229   rectangle representing the view. For instance, calling {@link android.view.View#getRight()}
230   is similar to the following computation: <code>getLeft() + getWidth()</code>.
231   </p>
232   
233
234<h2 id="SizePaddingMargins">Size, Padding and Margins</h2>
235   <p>
236   The size of a view is expressed with a width and a height. A view actually
237   possess two pairs of width and height values.
238   </p>
239  
240   <p>
241   The first pair is known as <em>measured width</em> and
242   <em>measured height</em>. These dimensions define how big a view wants to be
243   within its parent. The
244   measured dimensions can be obtained by calling {@link android.view.View#getMeasuredWidth()}
245   and {@link android.view.View#getMeasuredHeight()}.
246   </p>
247  
248   <p>
249   The second pair is simply known as <em>width</em> and <em>height</em>, or
250   sometimes <em>drawing width</em> and <em>drawing height</em>. These
251   dimensions define the actual size of the view on screen, at drawing time and
252   after layout. These values may, but do not have to, be different from the
253   measured width and height. The width and height can be obtained by calling
254   {@link android.view.View#getWidth()} and {@link android.view.View#getHeight()}. 
255   </p>
256  
257   <p>
258   To measure its dimensions, a view takes into account its padding. The padding
259   is expressed in pixels for the left, top, right and bottom parts of the view.
260   Padding can be used to offset the content of the view by a specific amount of
261   pixels. For instance, a left padding of 2 will push the view's content by
262   2 pixels to the right of the left edge. Padding can be set using the
263   {@link android.view.View#setPadding(int, int, int, int)} method and queried by calling
264   {@link android.view.View#getPaddingLeft()}, {@link android.view.View#getPaddingTop()},
265   {@link android.view.View#getPaddingRight()} and {@link android.view.View#getPaddingBottom()}.  
266   </p>
267  
268   <p>
269   Even though a view can define a padding, it does not provide any support for
270   margins. However, view groups provide such a support. Refer to
271   {@link android.view.ViewGroup} and
272   {@link android.view.ViewGroup.MarginLayoutParams} for further information.
273   </p>
274
275<p>For more information about dimensions, see <a href="{@docRoot}guide/topics/resources/available-resources.html#dimension">Dimension Values</a>.</p>
276   
277
278
279
280