Understanding Relative Layout in android

Understanding Relative Layout in android

Our last tutorial was Understanding Linear Layout in Android, if you have not seen it or read it I will suggest you take out time and go through it before you continue with this tutorial.

We went into details in discussing what android layout is all about but today we will focus on Relative Layout in Android.

Every layout file in android has a root View or ViewGroup. A ViewGroup is a subclass of a View. It can contain other View(s) or View Group(s). In our example of a relative layout, the layout file we will use to demonstrate this process will has a relative layout as the root element.

Before we go ahead and start with an example of how to implement Relative layout in android it is important to understand how relative layout work.

Relative layout is a ViewGroup that align its children in relative to each other or to their parent view. Relative layout also has different attributes. It uses its left, right, top and down constant values to arrange a view in a relative positive to other views

By default, all child views are drawn at the top-left of the layout, so you must define the position of each view by using layout properties called RelativeLayout LayoutParams.

Relative layout is one of the most used ViewGroups in android application development. This is because of its simplicity and flexibility to use. It affords android developers the opportunity to design a sleek and attractive user interface with ease of positioning different view components.

Another important thing to note is that relative layout can also be created in android programmatically. We will also learn how to achieve this after we must have done with the layout file.

The following list below itemize the different attributes present in a relative layout and what they can be used for.

android:layout_alignBottomMakes the bottom edge of this view match the bottom edge of the given anchor view ID.
android:layout_alignEndMakes the end edge of this view match the end edge of the given anchor view ID.
android:layout_alignLeftMakes the left edge of this view match the left edge of the given anchor view ID.
android:layout_alignParentBottomIf true, makes the bottom edge of this view match the bottom edge of the parent.
android:layout_alignParentEndIf true, makes the end edge of this view match the end edge of the parent.
android:layout_alignParentLeftIf true, makes the left edge of this view match the left edge of the parent.
android:layout_alignParentRightIf true, makes the right edge of this view match the right edge of the parent.
android:layout_alignParentStartIf true, makes the start edge of this view match the start edge of the parent.
android:layout_alignParentTopIf true, makes the top edge of this view match the top edge of the parent.
android:layout_alignRightMakes the right edge of this view match the right edge of the given anchor view ID.
android:layout_alignStartMakes the start edge of this view match the start edge of the given anchor view ID.
android:layout_alignTopMakes the top edge of this view match the top edge of the given anchor view ID.
android:layout_alignWithParentIfMissingIf set to true, the parent will be used as the anchor when the anchor cannot be found for layout_toLeftOf, layout_toRightOf, etc.
android:layout_belowPositions the top edge of this view below the given anchor view ID.
android:layout_centerHorizontalIf true, centers this child horizontally within its parent.
android:layout_centerInParentIf true, centers this child horizontally and vertically within its parent.
android:layout_centerVerticalIf true, centers this child vertically within its parent.
android:layout_toEndOfPositions the start edge of this view to the end of the given anchor view ID.
android:layout_toLeftOfPositions the right edge of this view to the left of the given anchor view ID.
android:layout_toRightOfPositions the left edge of this view to the right of the given anchor view ID.
android:layout_toStartOfPositions the end edge of this view to the start of the given anchor view ID.

Now that we are a bit familiar with relative layout, we will go ahead and create a new project that will demonstrate real life usage of a relative layout in android. In this example we are going to create a login application interface. The android project will contain a login page where users can add their login details in other to get access to secured pages in the application.

Create a new android project by following the steps listed below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: RelativeLayout

Package: com.inducesmile.relativelayout

Keep other default selections

Continue to click on next button until Finish button is active

Then click on Finish Button

Once you are done with your project, head over to the resource > layout folder and open the file called activity_main.xml. The code content of this file is pasted below

<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="com.inducesmile.relativelayout.MainActivity" >
</RelativeLayout>

Every layout file has a root ViewGroup. In our case the ViewGroup is a Relative Layout. The root also has xmlns:android attribute with a value of “http://schemas.android.com/apk/res/android”. xmlns:android initializes the namespace ‘android’.

The layout_width and layout_height is essential in every layout since it determines the width and height of the layout relative to android window.

To create our interface, we are going to add two TextView, two EditText and on Button View controls. You are free to try it out by yourself. You can also copy and paste the code below to your layout 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="com.inducesmile.relativelayout.MainActivity" >

TextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="40dp"
android:textStyle="bold"
android:text="@string/username" />

<EditText
android:id="@+id/username_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/username"
android:layout_below="@+id/username"
android:layout_marginTop="16dp"
android:inputType="text"
android:ems="10" >
<requestFocus />
</EditText>

<TextView
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/username_input"
android:layout_below="@+id/username_input"
android:layout_marginTop="40dp"
android:textStyle="bold"
android:text="@string/password" />

<EditText
android:id="@+id/password_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/password"
android:layout_below="@+id/password"
android:layout_marginTop="24dp"
android:ems="10"
android:inputType="textPassword" />

<Button
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/password_input"
android:layout_below="@+id/password_input"
android:layout_marginTop="40dp"
android:text="@string/login_button" />

</RelativeLayout>

relativeUI

In the layout code above, you will notice some lines of code like android:layout_alignLeft=”@+id/username”. This is how relative layout works in android. What that line of code is doing is to instruct the parent that it wants to align itself to a sibling view with the id it provided.

Let’s head over to out MainActivity.java file to demonstrate how we will tie everything together. As mentioned in our linear layout tutorial, Activity class uses its setContentview to set a View or ViewGroup it will use to build its user interface. This can be seen in onCreate call-back method of our Activity class.

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

We have also added some information in our project string.xml file to hold string values for our view names. The code snippet is shown below

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">RelativeLayout</string>
<string name="action_settings">Settings</string>
<string name="username">Username</string>
<string name="password">Password</string>
<string name="login_button">Login Button</string>
</resources>

The complete code for our activity class is shown below.

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

private EditText username;
private EditText password;

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

   username = (EditText)findViewById(R.id.username);
   password = (EditText)findViewById(R.id.password);

   Button loginButton = (Button)findViewById(R.id.login_button);
   loginButton.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View view) {
     // TODO Auto-generated method stub
     String usernameInput = username.getText().toString();
     String passwordInput = password.getText().toString();

     if(usernameInput.equals("") || passwordInput.equals("")){
             Toast.makeText(MainActivity.this, "Fields must be filled", Toast.LENGTH_SHORT).show();
       return;
     }
      Toast.makeText(MainActivity.this, "Valid login", Toast.LENGTH_SHORT).show();
      return;
     }
   });
 }
  
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
       // Handle action bar item clicks here. The action bar will
       // automatically handle clicks on the Home/Up button, so long
       // as you specify a parent activity in AndroidManifest.xml.
       int id = item.getItemId();
       if (id == R.id.action_settings) {
            return true;
       }
       return super.onOptionsItemSelected(item); 
   }

That brings us to the end of this tutorial. You can run your application and if everything looks good, your interface will be similar to the image displayed above.

Finally, if you have a question or suggestion kindly use our comment box. You can download the source code for this tutorial below.

No Responses

Add a Comment