RelativeLayout in Android (XML)

Public on January 1, 2009
RelativeLayout, from the word Relative, the concept here is that every children is a relative of the other. The catch here is that they are related by where you put them according to the other components, these relationship are above a component, below a component, on the left of the component and on the right of the components and some others like align to positions. Here we shall cover the above, below, left of, right of.
<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
>
  <Button android:id="@+id/topBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Top"
    android:layout_centerHorizontal="true">
  </Button>

  <Button android:id="@+id/leftBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Left"
    android:layout_below="@+id/topBtn"
    android:layout_toLeftOf="@+id/topBtn">
  </Button>

  <Button android:id="@+id/bottomBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Bottom"
    android:layout_below="@+id/leftBtn"
    android:layout_toRightOf="@+id/leftBtn">
  </Button>

  <Button android:id="@+id/rightBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Right"
    android:layout_above="@+id/bottomBtn"
    android:layout_toRightOf="@+id/bottomBtn"&
  </Button>
</RelativeLayout>


Quick Explanation
Here you shall see Top is aligned to the middle (android:layout_centerHorizontal="true"), the Left button is below top (android:layout_below="@+id/topBtn") and also is on its left. The Bottom is below leftBtn and on the right of leftBtn too. Lastly the Right is above and on the right of bottomBtn.

Further reading
RelativeLayout in Hello View in Android

Update History
   before 2012: Here is how you can set this as your layout in your java code
   Jan 17, 2012 - Visual Update




[Advertising]Faster Thinking - Speed up your brain


Faster Thinking Game



sentiment_satisfied Emoticon