Skip to main content

RelativeLayout Tutorial and Examples

RelativeLayout in Android.

RelativeLayout is a layout manager that allows you to position child views relative to each other or relative to the parent view. It is one of the most commonly used layout managers in Android development due to its flexibility and ease of use.

In this article, we will explain how to use RelativeLayout in Android using Kotlin. We will provide code examples to illustrate the concepts and steps involved.

Step 1: Create a new project

Create a new project in Android Studio and choose a blank activity. Give your project a name and select the language you want to use (Kotlin or Java).

Step 2: Add a RelativeLayout to your activity

Open the activity_main.xml file and replace the default layout with a RelativeLayout. You can add the following code to your XML file:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</RelativeLayout>

Step 3: Add child views to your RelativeLayout

You can add child views to your RelativeLayout by nesting them inside the RelativeLayout tag. Each child view can be positioned relative to the parent view or to other child views.

For example, you can add a TextView to your RelativeLayout and position it at the top of the screen by using the android:layout_alignParentTop attribute:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/title"
android:text="Hello World!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

</RelativeLayout>

Step 4: Position child views relative to each other

You can position child views relative to each other by using attributes such as android:layout_below, android:layout_above, android:layout_toRightOf, and android:layout_toLeftOf.

For example, you can add an ImageView below the TextView by using the android:layout_below attribute:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/title"
android:text="Hello World!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<ImageView
android:id="@+id/image"
android:src="@drawable/ic_launcher_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/title"
android:layout_centerHorizontal="true" />

</RelativeLayout>

Step 5: Use RelativeLayout inside other layouts

RelativeLayout can be used inside other layout managers such as LinearLayout and ScrollView. This allows you to create complex layouts that combine the strengths of different layout managers.

For example, you can use a LinearLayout to create a vertical layout with a RelativeLayout inside it:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
android:id="@+id/title"
android:text="Hello World!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<ImageView
android:id="@+id/image"
android:src="@drawable/ic_launcher_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/title"
android:layout_centerHorizontal="true" />

</RelativeLayout>

<TextView
android:text="This is a text view."
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>

Examples

Example 1: Design a Login Layout using RelativeLayout

This example teaches you how to design a functional login layout using RelativeLayout and widgets such as TextView, EditText and buttons.

Here is the demo screenshot:

login_relativelayout

Step 1: Create Project

Start by creating an empty Android Studio project.

Step 2: Dependencies

No special dependency is needed.

Step 3: Design Layout

Design layout as follows:

activity_main.xml

<?xml version="1.0" encoding="UTF-8"?>

<RelativeLayout
android:background="@color/greenplusblue"
tools:context=".MainActivity"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/activity_main"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">

<EditText
android:background="@android:color/white"
android:layout_height="30dp"
android:layout_width="match_parent"
android:id="@+id/editText2"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:textColorHint="@color/lightgrey"
android:hint="Email"
android:layout_above="@+id/editText3"
android:textColor="@android:color/background_dark"
android:ems="10"
android:inputType="textEmailAddress"/>

<EditText
android:background="@android:color/white"
android:layout_height="30dp"
android:layout_width="match_parent"
android:id="@+id/editText3"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginTop="10dp"
android:textColorHint="@color/lightgrey"
android:hint="Password"
android:layout_above="@+id/button"
android:ems="10"
android:inputType="textPassword"
android:selectAllOnFocus="false"
android:layout_marginBottom="22dp"/>

<Button
android:background="@color/lightgrey"
android:layout_height="30dp"
android:layout_width="match_parent"
android:id="@+id/button"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="LOGIN"/>

<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/textView"
android:text="Not a member?Sign up now"
android:layout_marginStart="98dp"
android:layout_marginLeft="98dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_below="@+id/button"
android:layout_marginTop="25dp"/>

</RelativeLayout>

Step 4: MainActivity

Here's the MainActivity:

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

NumberLink
1.Download Example
2.Follow code author

Quick Relative Layout Examples and HowTo's

1. How to design a custom toolbar with RelativeLayout

First we will need to create a layout, say tool_bar.xml.

We have a relativelayout as our root element, the width will match the parent while take note that the height will only be 50dp since this is a toolbar we are designing.

We will have a back button to the left. Then two textViews aligned vertically with our LinearLayout.

Then an imageview to the right of the toolbar.

<RelativeLayout

android_background="@color/colorPrimary"
android_layout_width="match_parent"
android_layout_height="50dp">

<Button
android_id="@+id/title_bar_back"
android_layout_width="40dp"
android_layout_height="40dp"
android_layout_marginLeft="5dp"
android_layout_centerVertical="true"
android_layout_alignParentLeft="true"
style="?borderlessButtonStyle"
android_foreground="?android:attr/selectableItemBackground"/>

<LinearLayout
android_orientation="vertical"
android_layout_width="wrap_content"
android_layout_height="match_parent"
android_layout_centerInParent="true">
<TextView
android_id="@+id/title_bar_text"
android_layout_weight="1"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_layout_gravity="center"
android_gravity="center"
android_text="TITLE"
android_textSize="20sp"
android_textColor="#fff" />
<TextView
android_id="@+id/title_bar_campus"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_layout_marginBottom="3dp"
android_textColor="#fff"
android_textSize="10sp"
android_layout_gravity="center"
android_gravity="center"
android_text="Software Campus"/>
</LinearLayout>

<ImageView
android_id="@+id/title_bar_right_button"
android_layout_width="40dp"
android_layout_height="40dp"
android_layout_marginRight="5dp"
android_layout_centerVertical="true"
android_layout_alignParentRight="true"
android_clickable="true"
android_foreground="?android:attr/selectableItemBackground"/>

</RelativeLayout>

Then we come and create a class, let's call it ToolBarView. This class will be deriving from the relativelayout class.

First as instance fields we will maintain a Button, TextViews and ImageView as widgets within our class.

Then we will create our constructor. This constructor has to take at least a Context object. In this case we will also pass an AttributeSet object.

Both will then be passed to the super class via the special super() method. Our super class in this case is the RelativeLayout class.

We will inflate our R.layout.tool_bar xml layout inside thei constructor. Then reference the widgets we mentioned above.

Here's the full code:

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
* Custom controls for the title bar
*/

public class ToolBarView extends RelativeLayout{

private Button backButton; //Return button
private TextView titleText; //Title text
private TextView titleCampus;
private ImageView rightButton; //Right button

public ToolBarView(Context context, AttributeSet attr) {

super(context, attr);

/**
* Load the ToolBar layout file
*/
LayoutInflater.from(context).inflate(R.layout.tool_bar, this);
titleText = (TextView) findViewById(R.id.title_bar_text);
backButton = (Button) findViewById(R.id.title_bar_back);
rightButton = (ImageView) findViewById(R.id.title_bar_right_button);

titleCampus = (TextView) findViewById(R.id.title_bar_campus);

setBackButtonVisible(false);

setTitleCampusVisible(false);

rightButton.setEnabled(false);

}

/**
* Set headline text
* @param titleText
*/
public void setTitleText(String titleText) {

this.titleText.setText(titleText);

}

/**
* Set the listen event for the back button
* @param listener
*/
public void setBackButtonOnClickListener(OnClickListener listener) {

backButton.setOnClickListener(listener);

}

/**
* Set the left button background image
* @param resourceId
*/
public void setBackButtonImage(int resourceId) {

backButton.setBackgroundResource(resourceId);

}

/**
* Set the right button background image
* @param resourceId
*/
public void setRightButtonImage(int resourceId) {

rightButton.setBackgroundResource(resourceId);

}

/**
* Set the right button to listen for events
* @param listener
*/
public void setRightButtonOnClickListener(OnClickListener listener) {

rightButton.setEnabled(true);

rightButton.setOnClickListener(listener);

}

public void setBackButtonVisible(boolean b) {
int state;
if (b) {
state = VISIBLE;
} else {
state = GONE;
}
backButton.setVisibility(state);
}

public void setTitleCampusVisible(boolean b) {
int state;
if (b) {
state = VISIBLE;
} else {
state = GONE;
}
titleCampus.setVisibility(state);
}

/**
* Set the title bar name
* @param campusCode
*/
public void setTitleCampus(int campusCode) {
titleCampus.setText(getCampusNameFromSomewhere(campusCode));
}

/**
* Back button click event
*/
public void callOnBackButtonClick() {
backButton.callOnClick();
}
}

Lastly let's see how we can use our ToolBarView as our toolbar. We need to do this in our activity.

But first you need to create a layout that will have our toolbar for our activity.

Let's say here's our activity_main.xml layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android_orientation="vertical"

android_layout_width="match_parent"
android_layout_height="match_parent"
tools_context="com.jshaz.daigo.EULAActivity">

<com.jshaz.daigo.ui.ToolBarView
android_id="@+id/eula_toolbar"
android_layout_width="match_parent"
android_layout_height="wrap_content"/>

<WebView
android_id="@+id/eula_webview"
android_layout_width="match_parent"
android_layout_height="match_parent"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity {

private ToolBarView toolBarView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

toolBarView = (ToolBarView) findViewById(R.id.eula_toolbar);

toolBarView.setTitleText("Main Activity");
toolBarView.setBackButtonImage(R.mipmap.icon_back);
toolBarView.setBackButtonVisible(true);
toolBarView.setBackButtonOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}

And that's it. We have created a custom toolbar from Relative layout.

2. How to create a Square RelativeLayout

First, let's have our SquareHelper class:


import android.content.res.TypedArray;
import android.support.annotation.IntDef;
import android.util.AttributeSet;
import android.view.View;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import online.sniper.R;

/**
* Square view helper class
* Created by wangpeihe on 2016/6/23.
*/
public class SquareHelper {

publicstaticfinalintBASE_WIDTH=0;
publicstaticfinalintBASE_HEIGHT=1;
publicstaticfinalintBASE_MIN_EDGE=2;
publicstaticfinalintBASE_MAX_EDGE=3;

@IntDef({BASE_WIDTH, BASE_HEIGHT, BASE_MAX_EDGE, BASE_MIN_EDGE})
@Retention(RetentionPolicy.SOURCE)
public @interface SquareViewEdge {

}

private View mView;
private int mBaseEdge = BASE_WIDTH;

public SquareHelper(View view, AttributeSet attrs) {
mView = view;
TypedArray a = view.getContext().obtainStyledAttributes(attrs, R.styleable.SquareView);
try {
mBaseEdge = a.getInt(R.styleable.SquareView_baseEdge, BASE_WIDTH);
} finally {
a.recycle();
}
}

public void setBaseEdge(@SquareViewEdge int baseEdge) {
mBaseEdge = baseEdge;
}

public int getMeasuredSize() {
switch (mBaseEdge) {
caseBASE_WIDTH:
return mView.getMeasuredWidth();
caseBASE_HEIGHT:
return mView.getMeasuredHeight();
caseBASE_MIN_EDGE:
return Math.min(mView.getMeasuredWidth(), mView.getMeasuredHeight());
caseBASE_MAX_EDGE:
return Math.max(mView.getMeasuredWidth(), mView.getMeasuredHeight());
default:
returnmView.getMeasuredWidth();
}
}

}

Then our SquareRelativeLayout

import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

public class SquareRelativeLayout extends RelativeLayout {

private final SquareHelper mHelper ;

public SquareRelativeLayout(Context context) {
this(context,null);
}

public SquareRelativeLayout(Context context, AttributeSet attrs) {
super(context,attrs);
mHelper=newSquareHelper( this,attrs);
}

@Override
protectedvoid onMeasure(intwidthMeasureSpec,intheightMeasureSpec){
super.onMeasure(widthMeasureSpec,heightMeasureSpec);
intsize=mHelper.getMeasuredSize();
int sizeSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
super.onMeasure(sizeSpec, sizeSpec);
}

}

Conclusion

RelativeLayout is a powerful and flexible layout manager that allows you to create complex layouts in Android. By following the steps outlined in this article, you can easily use RelativeLayout in your Android projects and create layouts that meet your specific needs.