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="http://schemas.android.com/apk/res/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"
android:layout width="wrap content" android:layout height="wrap content" android:layout below="@id/entry" android:layout alignParentRight="true" android:layout marginLeft="10px" android:text="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.
Was this article helpful?