blob: 43afdf7c386279b3e5effd189017d785e3f51ee5 [file] [log] [blame]
page.title=Declaring Layout
parent.title=Views and Layout
parent.link=index.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#LoadingTheResource">Loading the XML Resource</a></li>
<li><a href="#Position">Position</a></li>
<li><a href="#SizePaddingMargin">Size, Padding and Margins</a></li>
</ol>
</div>
</div>
<p>You can create your application's user interface in two ways:
<ul>
<li><strong>Declare UI elements statically, in XML</strong>. Android provides a straightforward XML
vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts. </li>
<li><strong>Instantiate screen elements at runtime</strong>. Your
application can refer to or create View or other class objects and manipulate their properties programmatically. </li>
</ul>
<p>One advantage of declaring your UI in XML is that it enables you to better separate the presentation of your application from the code that controls it's behavior. Your UI description is 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 and for a variety of device screen sizes or languages. Additionally, declaring in XML makes it easier to see the elements and structure of your UI, so it's easier to debug problems. </p>
<div class="sidebox">
<p>The <a href="{@docRoot}guide/developing/tools/adt.html">Android Development Tools</a>
(ADT) plugin for Eclipse offers a layout preview of your XML &mdash;
with the XML file opened, select the <strong>Layout</strong> tab.</p>
<p>You should also try the
<a href="{@docRoot}guide/developing/tools/hierarchy-viewer.html">Hierarchy Viewer</a> tool,
for debugging layouts &mdash; it reveals layout property values,
draws wireframes with padding/margin indicators, and full rendered views while
you debug on the emulator or device.</p>
</div>
<p>The Android framework gives you the flexibility to use either or both of these ways of 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>
<p>You build your application's UI in approximately the same way, whether you are declaring it in XML or programmatically. In both cases, your UI will be a tree structure that may include multiple View or Viewgroup subclasses. </p>
<p>In general, the XML vocabulary for declaring UI elements closely follows the structure and naming of the framework's UI-related 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. </p>
<p>However, note that the XML vocabulary for defining UI is not entirely identical to the framework's classes and methods. In some cases, there are slight naming differences. For
example, the EditText element has a <code>text</code> attribute that corresponds to
<code>EditText.setText()</code>. </p>
<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>
<p>To learn more about the available XML elements and attributes, as well as the format of the XML file, see <a
href="{@docRoot}guide/topics/resources/available-resources.html#layoutresources">Layout Resources</a>.</p>
</div>
<p>Using Android's XML vocabulary, you can quickly design UI layouts and the screen elements they contain, in the same way you create HTML files &mdash; as a series of nested tags. </p>
<p>Each layout file must contain exactly one root element, and the root element must be a View or ViewGroup object. Once you've defined the root element, you can add additional layout objects or controls as child elements of the root element, if needed. In the example below, the tree of XML elements evaluates to the outermost LinearLayout object.
<p>After you've declared your layout in XML, you must save the file, with the <code>.xml</code> extension,
in your application's <code>res/layout/</code> directory, so it will properly compile. </p>
<p>When you compile your application, each XML layout file is compiled into an
android.view.View resource. You can then load the layout resource from your application code, by calling <code>setContentView(R.layout.<em>layout_file_name</em>)</code> in your {@link android.app.Activity#onCreate(android.os.Bundle) Activity.onCreate()}
implementation.</p>
<p>When you load a layout resource, the Android system initializes run-time objects corresponding to the elements in your layout. It parses the elements of your layout in-order (depth-first), instantiating the Views and adding them to their parent(s).
See <a href="how-android-draws.html">How Android Draws Views</a> for more information.</p>
<p>Attributes named <code>layout_<em>something</em></code> apply to that
object's LayoutParams member. <a href="{@docRoot}guide/topics/resources/available-resources.html#layoutresources">Layout
Resources</a> also describes how to learn the syntax for specifying
LayoutParams properties. </p>
<p>Also note that Android draws elements in the order in which they
appear in the XML. Therefore, if elements overlap, the last one in the XML
file will probably be drawn on top of any previously listed elements in that
same space.</p>
<p>The following values are supported for dimensions (described in {@link
android.util.TypedValue TypedValue}):</p>
<ul>
<li>px (pixels) </li>
<li>dip (device independent pixels) </li>
<li>sp (scaled pixels &mdash; best for text size) </li>
<li>pt (points) </li>
<li>in (inches) </li>
<li>mm (millimeters) </li>
</ul>
<p>Example: <code>android:layout_width=&quot;25px&quot;</code> </p>
<p>For more information about these dimensions, see <a href="{@docRoot}guide/topics/resources/available-resources.html#dimension">Dimension Values</a>.</p>
<p>The example below shows an XML file and the resulting screen in the UI. Note that the text on the
top of the screen was set by calling {@link
android.app.Activity#setTitle(java.lang.CharSequence) Activity.setTitle}. Note
that the attributes that refer to relative elements (i.e., layout_toLeft)
refer to the ID using the syntax of a relative resource
(@id/<em>id_number</em>). </p>
<table border="1">
<tr>
<td>
<pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;!-- Demonstrates using a relative layout to create a form --&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android
android:layout_width=&quot;fill_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:background=&quot;@drawable/blue&quot;
android:padding=&quot;10px&quot;&gt;
&lt;TextView id=&quot;@+id/label&quot;
android:layout_width=&quot;fill_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:text=&quot;Type here:&quot;/&gt;
&lt;EditText id=&quot;@+id/entry&quot;
android:layout_width=&quot;fill_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:background=&quot;@android:drawable/editbox_background&quot;
android:layout_below=&quot;@id/label&quot;/&gt;
&lt;Button id=&quot;@+id/ok&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_below=&quot;@id/entry&quot;
android:layout_alignParentRight=&quot;true&quot;
android:layout_marginLeft=&quot;10px&quot;
android:text=&quot;OK&quot; /&gt;
&lt;Button android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_toLeftOf=&quot;@id/ok&quot;
android:layout_alignTop=&quot;@id/ok&quot;
android:text=&quot;Cancel&quot; /&gt;
&lt;/RelativeLayout&gt;</pre></td>
<td><img src="{@docRoot}images/designing_ui_layout_example.png" alt="Screen shot showing how this layout XML file is rendered." /></td>
</tr>
</table>
<h2 id="LoadingTheResource">Loading the XML Resource</h2>
<p>Loading the compiled layout resource is very easy, and done with a single
call in the activity's <code>onCreate()</code> method, as shown here:</p>
<pre>
protected void onCreate(Bundle savedInstanceState)
{
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// Load the compiled layout resource into the window's
// default ViewGroup.
// The source file is res/layout/hello_activity.xml
setContentView(R.layout.hello_activity);
// Retrieve any important stored values.
restoreValues(savedInstanceState);
} </pre>
<h2 id="Position">Position</h2>
<p>
The geometry of a view is that of a rectangle. A view has a location,
expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
two dimensions, expressed as a width and a height. The unit for location
and dimensions is the pixel.
</p>
<p>
It is possible to retrieve the location of a view by invoking the methods
{@link android.view.View#getLeft()} and {@link android.view.View#getTop()}. The former returns the left, or X,
coordinate of the rectangle representing the view. The latter returns the
top, or Y, coordinate of the rectangle representing the view. These methods
both return the location of the view relative to its parent. For instance,
when getLeft() returns 20, that means the view is located 20 pixels to the
right of the left edge of its direct parent.
</p>
<p>
In addition, several convenience methods are offered to avoid unnecessary
computations, namely {@link android.view.View#getRight()} and {@link android.view.View#getBottom()}.
These methods return the coordinates of the right and bottom edges of the
rectangle representing the view. For instance, calling {@link android.view.View#getRight()}
is similar to the following computation: <code>getLeft() + getWidth()</code>.
</p>
<h2 id="SizePaddingMargins">Size, Padding and Margins</h2>
<p>
The size of a view is expressed with a width and a height. A view actually
possess two pairs of width and height values.
</p>
<p>
The first pair is known as <em>measured width</em> and
<em>measured height</em>. These dimensions define how big a view wants to be
within its parent. The
measured dimensions can be obtained by calling {@link android.view.View#getMeasuredWidth()}
and {@link android.view.View#getMeasuredHeight()}.
</p>
<p>
The second pair is simply known as <em>width</em> and <em>height</em>, or
sometimes <em>drawing width</em> and <em>drawing height</em>. These
dimensions define the actual size of the view on screen, at drawing time and
after layout. These values may, but do not have to, be different from the
measured width and height. The width and height can be obtained by calling
{@link android.view.View#getWidth()} and {@link android.view.View#getHeight()}.
</p>
<p>
To measure its dimensions, a view takes into account its padding. The padding
is expressed in pixels for the left, top, right and bottom parts of the view.
Padding can be used to offset the content of the view by a specific amount of
pixels. For instance, a left padding of 2 will push the view's content by
2 pixels to the right of the left edge. Padding can be set using the
{@link android.view.View#setPadding(int, int, int, int)} method and queried by calling
{@link android.view.View#getPaddingLeft()}, {@link android.view.View#getPaddingTop()},
{@link android.view.View#getPaddingRight()} and {@link android.view.View#getPaddingBottom()}.
</p>
<p>
Even though a view can define a padding, it does not provide any support for
margins. However, view groups provide such a support. Refer to
{@link android.view.ViewGroup} and
{@link android.view.ViewGroup.MarginLayoutParams} for further information.
</p>