Absolute Layout in Android
An Absolute Layout allows you to specify the exact location i.e. X and Y coordinates of its children with respect to the origin at the top left corner of the layout. The absolute layout is less flexible and harder to maintain for varying sizes of screens that's why it is not recommended. Although Absolute Layout is deprecated now.
Some of the important Absolute Layout attributes are the following:
- android:id: It uniquely specifies the absolute layout
- android:layout_x: It specifies X-Coordinate of the Views (Possible values of this are in density-pixel or pixel)
- android:layout_y: It specifies Y-Coordinate of the Views (Possible values of this are in dp or px)
Syntax for Absolute Layout:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--sub view 1-->
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!--sub view 2-->
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</AbsoluteLayout>
Example: In this example, we are going to create a basic application with Absolute Layout that is having two sample views with a background.
Note that we are going to implement this project using the Java language.
Step by Step Implementation
Let us follow the steps to demonstrate the Absolute Layout in Android.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Create the layout file
For this go to app > res > layout > activity_main.xml file and change the Constraint Layout to Absolute Layout and add 3 sample views. Below is the code snippet for the activity_main.xml file.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
tools:context=".MainActivity">
<!--sub view 1-->
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@color/green"
android:layout_x="0dp"
android:layout_y="0dp"/>
<!--sub view 2-->
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@color/green"
android:layout_x="150dp"
android:layout_y="150dp"/>
<!--sub view 3-->
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@color/green"
android:layout_x="300dp"
android:layout_y="300dp"/>
</AbsoluteLayout>
Output: You will see that views are having fixed X and Y Coordinates.
