Relative Layout

RelativeLayout lets child views specify their position relative to the parent view or to each other (specified by ID). So you can align two elements by right border, or make one below another, centered in the screen, centered left, and so on. Elements are rendered in the order given, so if the first element is centered in the screen, other elements aligning themselves to that element will be aligned relative to screen center. Also, because of this ordering, if using XML to specify this layout, the element that you will reference (in order to position other view objects) must be listed in the XML file before you refer to it from the other views via its reference ID.

The example below shows an XML file and the resulting screen in the UI. Note that the attributes that refer to relative elements (e.g., layout_toLeft) refer to the ID using the syntax of a relative resource (@id/id).

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/blue" android:padding="10px" >

<TextView android:id="@+id/label"

android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Type here:" />

<EditText android:id="@+id/entry"

android:layout_width="fill_parent" android:layout_height="wrap_content"

android:background="@android:drawable/editbox_background" android:layout_below="@id/label" />

<Button android:id="@+id/ok"






<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toLeftOf="@id/ok" android:layout_alignTop="@id/ok" android:text="Cancel" /> </RelativeLayout>

Some of these properties are supported directly by the element, and some are supported by its LayoutParams member (subclass RelativeLayout for all the elements in this screen, because all elements are children of a RelativeLayout parent object). The defined RelativeLayout parameters are: width, height, below, alignTop, toLeft, padding[Bottom|Left|Right|Top], and margin[Bottom|Left|Right|Top]. Note that some of these parameters specifically support relative layout positions — their values must be the ID of the element to which you'd like this view laid relative. For example, assigning the parameter toLeft="my_button" to a TextView would place the TextView to the left of the View with the ID my_button (which must be written in the XML before the TextView).

To view this sample code, see the Hello RelativeLayout tutorial.

0 0

Post a comment