How to use RelativeLayout in an Android app?

In Android development, a RelativeLayout is a view group that displays child views in relative positions. It allows you to position your UI components relative to each other or to the parent layout. This is particularly useful for creating complex layouts without requiring nested view groups, which can potentially lead to performance issues.

How to Use RelativeLayout

To use a RelativeLayout in your layout XML file, you need to specify it as the root element and then define your child views with their respective layout parameters that establish their positions.

Example of RelativeLayout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/text1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, World!" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" android:layout_below="@id/text1" android:layout_centerHorizontal="true" /> </RelativeLayout>

This example demonstrates a simple RelativeLayout with a TextView centered at the top and a Button positioned below it.


Android RelativeLayout Android UI Components Android Layouts View Group Relative Positioning