The most common way to define your layout and express the view hierarchy is with an XML layout file. XML offers a human-readable structure for the layout, much like HTML. Each element in XML is either a View or ViewGroup object (or descendent thereof). View objects are leaves in the tree, ViewGroup objects are branches in the tree (see the View Hierarchy figure above).

The name of an XML element is respective to the Java class that it represents. So a <TextView> element creates a TextView in your UI, and a <LinearLayout> element creates a LinearLayout view group. When you load a layout resource, the Android system initializes these run-time objects, corresponding to the elements in your layout.

For example, a simple vertical layout with a text view and a button looks like this:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="" android:layout_width="fill_parent" android:layout height="fill 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>

Notice that the LinearLayout element contains both the TextView and the Button. You can nest another LinearLayout (or other type of view group) inside here, to lengthen the view hierarchy and create a more complex layout.

For more on building a UI layout, read Declaring Layout.

Tip: You can also draw View and ViewGroups objects in Java code, using the addView(View) methods to dynamically insert new View and ViewGroup objects.

There are a variety of ways in which you can layout your views. Using more and different kinds of view groups, you can structure child views and view groups in an infinite number of ways. Some pre-defined view groups offered by Android (called layouts) include LinearLayout, RelativeLayout, TableLayout, GridLayout and others. Each offers a unique set of layout parameters that are used to define the positions of child views and layout structure.

To learn about some of the different kinds of view groups used for a layout, read Common Layout Objects.

0 0

Post a comment