Anchor Views

Description

Anchoring can be easily achieved by using RelativeLayout.

Example

Consider the following main.xml file, which contains five Button views embedded within the <RelativeLayout> element:


<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Top Left"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Top Right"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true" />
    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bottom Left"
        android:layout_alignParentLeft="true"
        android:layout_alignParentBottom="true" />
    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bottom Right"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true" />
    <Button
        android:id="@+id/button5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Middle"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>


Anchor Views

Note

The following attributes found in the various Button views:

  • layout_alignParentLeft aligns the view to the left of the parent view
  • layout_alignParentRight aligns the view to the right of the parent view
  • layout_alignParentTop aligns the view to the top of the parent view
  • layout_alignParentBottom aligns the view to the bottom of the parent view
  • layout_centerVertical centers the view vertically within its parent view
  • layout_centerHorizontal centers the view horizontally within its parent view

When the screen orientation is changed, the four buttons are aligned to the four edges of the screen, and the center button is centered in the middle of the screen with its width fully stretched.





















Home »
  Android »
    Android Basics »




Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS