Hello Relative Layout

A RelativeLayout is a ViewGroup that allows you to layout child elements in positions relative to the parent or siblings elements.

1. Start a new project/Activity called HelloRelativeLayout.

2. Open the layout file. Make it like so:

<?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="fill parent">

<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="10dip"

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>

Pay attention to each of the additional layout * attributes (besides the usual width and height, which are required for all elements). When using relative layout, we use attributes likelayout below and layout toLeftOf to describe how we'd like to position each View. Naturally, these are different relative positions, and the value of the attribute is the id of the element we want the position relative to.

3. Make sure your Activity loads this layout in the onCreate() method:

Pay attention to each of the additional layout * attributes (besides the usual width and height, which are required for all elements). When using relative layout, we use attributes likelayout below and layout toLeftOf to describe how we'd like to position each View. Naturally, these are different relative positions, and the value of the attribute is the id of the element we want the position relative to.

3. Make sure your Activity loads this layout in the onCreate() method:

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

R.layout.main refers to the main.xml layout file

You should see the following:

Resources

• RelativeLayout

Was this article helpful?

0 0

Post a comment