page.title=Layouts page.tags=view,viewgroup @jd:body <div id="qv-wrapper"> <div id="qv"> <h2>In this document</h2> <ol> <li><a href="#write">Write the XML</a></li> <li><a href="#load">Load the XML Resource</a></li> <li><a href="#attributes">Attributes</a> <ol> <li><a href="#id">ID</a></li> <li><a href="#layout-params">Layout Parameters</a></li> </ol> </li> <li><a href="#Position">Layout Position</a></li> <li><a href="#SizePaddingMargins">Size, Padding and Margins</a></li> <li><a href="#CommonLayouts">Common Layouts</a></li> <li><a href="#AdapterViews">Building Layouts with an Adapter</a> <ol> <li><a href="#FillingTheLayout">Filling an adapter view with data</a></li> <li><a href="#HandlingUserSelections">Handling click events</a></li> </ol> </li> </ol> <h2>Key classes</h2> <ol> <li>{@link android.view.View}</li> <li>{@link android.view.ViewGroup}</li> <li>{@link android.view.ViewGroup.LayoutParams}</li> </ol> <h2>See also</h2> <ol> <li><a href="{@docRoot}training/basics/firstapp/building-ui.html">Building a Simple User Interface</a></li> </div> </div> <p>A layout defines the visual structure for a user interface, such as the UI for an <a href="{@docRoot}guide/components/activities.html">activity</a> or <a href="{@docRoot}guide/topics/appwidgets/index.html">app widget</a>. You can declare a layout in two ways:</p> <ul> <li><strong>Declare UI elements 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 layout elements at runtime</strong>. Your application can create View and ViewGroup objects (and manipulate their properties) programmatically. </li> </ul> <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> <div class="sidebox-wrapper"> <div class="sidebox"> <ul> <li>You should also try the <a href="{@docRoot}tools/debugging/debugging-ui.html#hierarchyViewer">Hierarchy Viewer</a> tool, for debugging layouts — it reveals layout property values, draws wireframes with padding/margin indicators, and full rendered views while you debug on the emulator or device.</li> <li>The <a href="{@docRoot}tools/debugging/debugging-ui.html#layoutopt">layoutopt</a> tool lets you quickly analyze your layouts and hierarchies for inefficiencies or other problems.</li> </div> </div> <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 interested in instantiating View objects at runtime, refer to the {@link android.view.ViewGroup} and {@link android.view.View} class references.</p> <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 example, the EditText element has a <code>text</code> attribute that corresponds to <code>EditText.setText()</code>. </p> <p class="note"><strong>Tip:</strong> Learn more about different layout types in <a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>.</p> <h2 id="write">Write the XML</h2> <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 — with a series of nested elements. </p> <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} to hold a {@link android.widget.TextView} and a {@link android.widget.Button}:</p> <pre> <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a TextView" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button" /> </LinearLayout> </pre> <p>After you've declared your layout in XML, save the file with the <code>.xml</code> extension, in your Android project's <code>res/layout/</code> directory, so it will properly compile. </p> <p>More information about the syntax for a layout XML file is available in the <a href="{@docRoot}guide/topics/resources/layout-resource.html">Layout Resources</a> document.</p> <h2 id="load">Load the XML Resource</h2> <p>When you compile your application, each XML layout file is compiled into a {@link android.view.View} resource. You should load the layout resource from your application code, in your {@link android.app.Activity#onCreate(android.os.Bundle) Activity.onCreate()} callback implementation. Do so by calling <code>{@link android.app.Activity#setContentView(int) setContentView()}</code>, passing it the reference to your layout resource in the form of: <code>R.layout.<em>layout_file_name</em></code>. For example, if your XML layout is saved as <code>main_layout.xml</code>, you would load it for your Activity like so:</p> <pre> public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); } </pre> <p>The <code>onCreate()</code> callback method in your Activity is called by the Android framework when your Activity is launched (see the discussion about lifecycles, in the <a href="{@docRoot}guide/components/activities.html#Lifecycle">Activities</a> document).</p> <h2 id="attributes">Attributes</h2> <p>Every View and ViewGroup object supports their own variety of XML attributes. Some attributes are specific to a View object (for example, TextView supports the <code>textSize</code> attribute), but these attributes are also inherited by any View objects that may extend this class. Some are common to all View objects, because they are inherited from the root View class (like the <code>id</code> attribute). And, other attributes are considered "layout parameters," which are attributes that describe certain layout orientations of the View object, as defined by that object's parent ViewGroup object.</p> <h3 id="id">ID</h3> <p>Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the <code>id</code> attribute. This is an XML attribute common to all View objects (defined by the {@link android.view.View} class) and you will use it very often. The syntax for an ID, inside an XML tag is:</p> <pre>android:id="@+id/my_button"</pre> <p>The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the <code>R.java</code> file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the <code>android</code> package namespace, like so:</p> <pre>android:id="@android:id/empty"</pre> <p>With the <code>android</code> package namespace in place, we're now referencing an ID from the <code>android.R</code> resources class, rather than the local resources class.</p> <p>In order to create views and reference them from the application, a common pattern is to:</p> <ol> <li>Define a view/widget in the layout file and assign it a unique ID: <pre> <Button android:id="@+id/my_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/my_button_text"/> </pre> </li> <li>Then create an instance of the view object and capture it from the layout (typically in the <code>{@link android.app.Activity#onCreate(Bundle) onCreate()}</code> method): <pre> Button myButton = (Button) findViewById(R.id.my_button); </pre> </li> </ol> <p>Defining IDs for view objects is important when creating a {@link android.widget.RelativeLayout}. In a relative layout, sibling views can define their layout relative to another sibling view, which is referenced by the unique ID.</p> <p>An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching (which may often be the entire tree, so it's best to be completely unique when possible).</p> <h3 id="layout-params">Layout Parameters</h3> <p>XML layout attributes named <code>layout_<em>something</em></code> define layout parameters for the View that are appropriate for the ViewGroup in which it resides.</p> <p>Every ViewGroup class implements a nested class that extends {@link android.view.ViewGroup.LayoutParams}. This subclass contains property types that define the size and position for each child view, as appropriate for the view group. As you can see in figure 1, the parent view group defines layout parameters for each child view (including the child view group).</p> <img src="{@docRoot}images/layoutparams.png" alt="" /> <p class="img-caption"><strong>Figure 1.</strong> Visualization of a view hierarchy with layout parameters associated with each view.</p> <p>Note that every LayoutParams subclass has its own syntax for setting values. Each child element must define LayoutParams that are appropriate for its parent, though it may also define different LayoutParams for its own children. </p> <p>All view groups include a width and height (<code>layout_width</code> and <code>layout_height</code>), and each view is required to define them. Many LayoutParams also include optional margins and borders. <p> <p>You can specify width and height with exact measurements, though you probably won't want to do this often. More often, you will use one of these constants to set the width or height: </p> <ul> <li><var>wrap_content</var> tells your view to size itself to the dimensions required by its content.</li> <li><var>match_parent</var> tells your view to become as big as its parent view group will allow.</li> </ul> <p>In general, specifying a layout width and height using absolute units such as pixels is not recommended. Instead, using relative measurements such as density-independent pixel units (<var>dp</var>), <var>wrap_content</var>, or <var>match_parent</var>, is a better approach, because it helps ensure that your application will display properly across a variety of device screen sizes. The accepted measurement types are defined in the <a href="{@docRoot}guide/topics/resources/available-resources.html#dimension"> Available Resources</a> document.</p> <h2 id="Position">Layout 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 <code>getLeft()</code> 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 number 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> <p>For more information about dimensions, see <a href="{@docRoot}guide/topics/resources/more-resources.html#Dimension">Dimension Values</a>. </p> <style type="text/css"> div.layout { float:left; width:200px; margin:0 0 20px 20px; } div.layout.first { margin-left:0; clear:left; } </style> <h2 id="CommonLayouts">Common Layouts</h2> <p>Each subclass of the {@link android.view.ViewGroup} class provides a unique way to display the views you nest within it. Below are some of the more common layout types that are built into the Android platform.</p> <p class="note"><strong>Note:</strong> Although you can nest one or more layouts within another layout to acheive your UI design, you should strive to keep your layout hierarchy as shallow as possible. Your layout draws faster if it has fewer nested layouts (a wide view hierarchy is better than a deep view hierarchy).</p> <!-- <h2 id="framelayout">FrameLayout</h2> <p>{@link android.widget.FrameLayout FrameLayout} is the simplest type of layout object. It's basically a blank space on your screen that you can later fill with a single object — for example, a picture that you'll swap in and out. All child elements of the FrameLayout are pinned to the top left corner of the screen; you cannot specify a different location for a child view. Subsequent child views will simply be drawn over previous ones, partially or totally obscuring them (unless the newer object is transparent). </p> --> <div class="layout first"> <h4><a href="layout/linear.html">Linear Layout</a></h4> <a href="layout/linear.html"><img src="{@docRoot}images/ui/linearlayout-small.png" alt="" /></a> <p>A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen.</p> </div> <div class="layout"> <h4><a href="layout/relative.html">Relative Layout</a></h4> <a href="layout/relative.html"><img src="{@docRoot}images/ui/relativelayout-small.png" alt="" /></a> <p>Enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent).</p> </div> <div class="layout"> <h4><a href="{@docRoot}guide/webapps/webview.html">Web View</a></h4> <a href="{@docRoot}guide/webapps/webview.html"><img src="{@docRoot}images/ui/webview-small.png" alt="" /></a> <p>Displays web pages.</p> </div> <h2 id="AdapterViews" style="clear:left">Building Layouts with an Adapter</h2> <p>When the content for your layout is dynamic or not pre-determined, you can use a layout that subclasses {@link android.widget.AdapterView} to populate the layout with views at runtime. A subclass of the {@link android.widget.AdapterView} class uses an {@link android.widget.Adapter} to bind data to its layout. The {@link android.widget.Adapter} behaves as a middleman between the data source and the {@link android.widget.AdapterView} layout—the {@link android.widget.Adapter} retrieves the data (from a source such as an array or a database query) and converts each entry into a view that can be added into the {@link android.widget.AdapterView} layout.</p> <p>Common layouts backed by an adapter include:</p> <div class="layout first"> <h4><a href="layout/listview.html">List View</a></h4> <a href="layout/listview.html"><img src="{@docRoot}images/ui/listview-small.png" alt="" /></a> <p>Displays a scrolling single column list.</p> </div> <div class="layout"> <h4><a href="layout/gridview.html">Grid View</a></h4> <a href="layout/gridview.html"><img src="{@docRoot}images/ui/gridview-small.png" alt="" /></a> <p>Displays a scrolling grid of columns and rows.</p> </div> <h3 id="FillingTheLayout" style="clear:left">Filling an adapter view with data</h3> <p>You can populate an {@link android.widget.AdapterView} such as {@link android.widget.ListView} or {@link android.widget.GridView} by binding the {@link android.widget.AdapterView} instance to an {@link android.widget.Adapter}, which retrieves data from an external source and creates a {@link android.view.View} that represents each data entry.</p> <p>Android provides several subclasses of {@link android.widget.Adapter} that are useful for retrieving different kinds of data and building views for an {@link android.widget.AdapterView}. The two most common adapters are:</p> <dl> <dt>{@link android.widget.ArrayAdapter}</dt> <dd>Use this adapter when your data source is an array. By default, {@link android.widget.ArrayAdapter} creates a view for each array item by calling {@link java.lang.Object#toString()} on each item and placing the contents in a {@link android.widget.TextView}. <p>For example, if you have an array of strings you want to display in a {@link android.widget.ListView}, initialize a new {@link android.widget.ArrayAdapter} using a constructor to specify the layout for each string and the string array:</p> <pre> ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myStringArray); </pre> <p>The arguments for this constructor are:</p> <ul> <li>Your app {@link android.content.Context}</li> <li>The layout that contains a {@link android.widget.TextView} for each string in the array</li> <li>The string array</li> </ul> <p>Then simply call {@link android.widget.ListView#setAdapter setAdapter()} on your {@link android.widget.ListView}:</p> <pre> ListView listView = (ListView) findViewById(R.id.listview); listView.setAdapter(adapter); </pre> <p>To customize the appearance of each item you can override the {@link java.lang.Object#toString()} method for the objects in your array. Or, to create a view for each item that's something other than a {@link android.widget.TextView} (for example, if you want an {@link android.widget.ImageView} for each array item), extend the {@link android.widget.ArrayAdapter} class and override {@link android.widget.ArrayAdapter#getView getView()} to return the type of view you want for each item.</p> </dd> <dt>{@link android.widget.SimpleCursorAdapter}</dt> <dd>Use this adapter when your data comes from a {@link android.database.Cursor}. When using {@link android.widget.SimpleCursorAdapter}, you must specify a layout to use for each row in the {@link android.database.Cursor} and which columns in the {@link android.database.Cursor} should be inserted into which views of the layout. For example, if you want to create a list of people's names and phone numbers, you can perform a query that returns a {@link android.database.Cursor} containing a row for each person and columns for the names and numbers. You then create a string array specifying which columns from the {@link android.database.Cursor} you want in the layout for each result and an integer array specifying the corresponding views that each column should be placed:</p> <pre> String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}; int[] toViews = {R.id.display_name, R.id.phone_number}; </pre> <p>When you instantiate the {@link android.widget.SimpleCursorAdapter}, pass the layout to use for each result, the {@link android.database.Cursor} containing the results, and these two arrays:</p> <pre> SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.person_name_and_number, cursor, fromColumns, toViews, 0); ListView listView = getListView(); listView.setAdapter(adapter); </pre> <p>The {@link android.widget.SimpleCursorAdapter} then creates a view for each row in the {@link android.database.Cursor} using the provided layout by inserting each {@code fromColumns} item into the corresponding {@code toViews} view.</p>.</dd> </dl> <p>If, during the course of your application's life, you change the underlying data that is read by your adapter, you should call {@link android.widget.ArrayAdapter#notifyDataSetChanged()}. This will notify the attached view that the data has been changed and it should refresh itself.</p> <h3 id="HandlingUserSelections">Handling click events</h3> <p>You can respond to click events on each item in an {@link android.widget.AdapterView} by implementing the {@link android.widget.AdapterView.OnItemClickListener} interface. For example:</p> <pre> // Create a message handling object as an anonymous class. private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { // Do something in response to the click } }; listView.setOnItemClickListener(mMessageClickedHandler); </pre>