×

Relative Layout


What is Relative Layout?

Relative Layout is used to align the UI elements horizontally and vertically based on the relative position of its parent element. Relative layout looks like this, Bars here represents the UI element like Label,Button,EditText ec.


Example :-


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp" >
    <EditText
        android:id="@+id/firstName"
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:hint="First Name"
        android:layout_alignParentLeft="true"
        />

    <EditText
        android:id="@+id/lastName"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:hint="Last Name"
        android:layout_toLeftOf="@+id/firstName"
        android:layout_alignParentRight="true"
        />

    <EditText
        android:id="@+id/country"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Country"
        android:layout_below="@+id/firstName"
        />

    <Button
        android:layout_width="96dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/country"
        android:layout_alignParentRight="true"
        android:text="Register" />

We discussed in detail about match_parent and wrap_cotent in previous tutorial. paddingLeft and paddingRight are used to specify the left & right position of UI element view. EditText is used to create the textfield and you can assign placeholder using android:hint attribute. Button is used to create the Button and you can assign layout gravity to place the button in left,right,center direction.

Whats new in Relative Layout?

As you see in the output image, First name EditText is on left side , Last Name EditText is toLeftOf of Firstname. Country EditText is below the firstName or Lastname and Button is below the Country EditTextField. Now look at the code, you can easily understand that we used toLeftOf attribute and assigned it the id to detect the relative element.

Now we want lastName to be on the left of first name but you must specify the right position of last name by using layout_alignParentRight .

 android:layout_toLeftOf="@+id/firstName"
      android:layout_alignParentRight="true"

Output :-