Linux.com

Home Learn Linux Linux Tutorials Android App Development for Beginners: Layout and UI Options, Part Two

Android App Development for Beginners: Layout and UI Options, Part Two

Following on from last month's tutorial on the basics of layout, and in particular LinearLayout, in this tutorial we'll look at RelativeLayout, and at how you can reuse layouts easily with theinclude directive. Getting a firm grip on how Android layout works is a big help towards making your beginner app into something that looks good and has great UI. Check out last month's tutorial for the basics of XML and resource management if there's anything here you don't recognize. We'll reuse the basic code structure from that tutorial. (See Android App Development for Beginners: Layout and UI Options, Part One.)

RelativeLayout

With LinearLayout, you can only display your various elements stacked next to each other or one above the other (although you can nest LinearLayouts to do both of these in the same layout). RelativeLayout is much more flexible, allowing you to specify the position of each child element relative to its parent or to another named element. One of the big advantages to using RelativeLayout over nested LinearLayouts is that nested view groups have a performance impact. If you can translate your nested LinearLayout into a single RelativeLayout, it's almost always a good idea to do so.

First up, let's replace our nested LinearLayout from the last tutorial with a single RelativeLayout. What we want is a TextView, an EditText below it, and two buttons below that. Using the same Activity as for the last tutorial, create a file activity_relativelayout.xml:

<?xml version="1.0" encoding="utf-8"?>
<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" >
    
    <TextView
        android:id="@+id/helloTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="@string/hello" />
    
    <EditText
       android:id="@+id/nameEditText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/helloTextView"
        android:hint="@string/name" />
    
    <Button
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/nameEditText"
        android:layout_alignParentLeft="true"
        android:text="@string/setName" />
    <Button
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/nameEditText"
        android:layout_alignParentRight="true"
        android:text="@string/clearName" />
</RelativeLayout>

You'll also need to change the layout reference in LayoutTestActivity to our new layout file:

public class LayoutTestActivity extends Activity {
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_relativelayout);
  }
}

Run this, and you should see a layout like the image below.

android relativelayout 1

All the elements have height "wrap content", so they're just as tall as their content. The buttons have a specific width (which you can play around with it to find out what looks good).

The important new layout attributes are layout_alignParentToplayout_alignParentRightlayout_alignParentLeft, and layout_below. The names make it fairly clear what they do: these are the layout attributes that allow you to describe the alignment of elements relative to other elements. The 'parent' element here is the RelativeLayout itself; all other elements in this layout are its children. The layout_below (or layout_above, etc) attribute allows you to specify a layout relative to another named child element. There are a stack of more options available, too — check out the the RelativeLayout.LayoutParams API to see them all.

Centring and distributing elements

You'll notice that the TextView above isn't centered. To center it, you have two options. The first is to make the element fill the parent, then center the text within the element:

<TextView
        android:layout_width="fill_parent"
        android:gravity="center" />

The second is to make the element a specific size (here, wrapping its content), then center the whole element within its parent:

<TextView
        android:layout_width="wrap_content"
        android:layout_centerHorizontal="true" />

You may need to combine these if you want an element to have a specific width that is wider than its content, but also want to center the element within its parent.

android relativelayout

You can't use the weight property (which we used in the last tutorial) in a RelativeLayout. This means that you can't spread your elements across the whole parent container by allocating them a weight. Instead, if you want to spread your elements out, you'll need to specify a width/height in dp. If using weight is important for your layout, you'll need to use a LinearLayout.

Aligning edges

Here's another way of laying out the elements to produce the same effect:

<TextView
  android:id="@+id/helloTextView"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_centerHorizontal="true"
  android:layout_alignParentStart="true"
  android:text="@string/hello" />
    
<EditText
  android:id="@+id/nameEditText"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_below="@id/helloTextView"
  android:hint="@string/name" />
    
<Button
  android:id="@+id/setNameButton"
  android:layout_width="150dp"
  android:layout_height="wrap_content"
  android:layout_below="@id/nameEditText"
  android:layout_toEndOf="@id/nameEditText"
  android:text="@string/setName" />
<Button
  android:layout_width="150dp"
  android:layout_height="wrap_content"
  android:layout_below="@id/nameEditText"
  android:layout_toRightOf="@id/setNameButton"
  android:text="@string/clearName" />

Attributes that look like layout_toEndOf align the start edge of that element to the end edge of the referenced element. (layout_toStartOf aligns the element's end edge to the start edge of the referenced element). Check the API docs for specific details of which edge aligns to which. This layout will look much like the previous layout, but the buttons are slightly to the left of center. This is because the second button is arranged to the right of the first button, rather than aligned with the parent's right edge as it was before. You can play around with adding padding or a margin to see how that affects the position, too.

android relativelayout

If you remove the layout_below line from the two buttons, you'll get them overlaid on the previous element. This is because the edges will be aligned, but without moving them down underneath the reference element. 

android relativelayout 4

Try out the various layout options to get a feel for how they work with one another. The full list of parameters is available at the RelativeLayout.LayoutParams API reference page.

Reusing layouts

Finally, a quick note that you can reuse layouts by using the include tag. Let's say we want to reuse the RelativeLayout above. It must look exactly as you want to use it wherever you're about to include it. Now let's set up a LinearLayout (include_layout_test.xml) to drop it into:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView
        android:id="@+id/helloTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_alignParentStart="true"
        android:text="@string/includetest" />
    
    <include layout="@layout/activity_relativelayout" />
</LinearLayout>

As you can see in the screenshot, this does exactly what you want it to, including the RelativeLayout underneath the TextView.

android relativelayout 5

Being able to reuse XML layouts like this has obvious advantages in terms of making a consistent (and maintainably consistent) look and feel across your app. Set up your repeatedly used text bar or button group in its own XML file, and include it wherever you want it to appear.

For more Android app development tutorials in this series see:

Android App Development for Beginners: Layout and UI Options, Part One

Android App Development: Handling Extra Camera Capabilities

Android App Development: How to Capture Video

 

Comments

Subscribe to Comments Feed
  • Puneet Said:

    Good post for beginners. Keep posting stuffs like this, my appreciations sir. :)

  • S J Bond Said:

    Thanks for sharing worthwhile information. Android applications development is a process of creating new applications for android operating system. These days the demand of smart phone is being increased, so the demands of the applications for these smart clients are constantly increasing.

  • Android App Development Said:

    What a great blog, i am searching in Google from couple of days.Two Simple Ways to Get Traffic to Your Blog” but did not find any great way,but my search came to an end after visiting your blog.

  • Parveen Joshi Said:

    Like the need for Android mobile phone grows, so does the need for application development of the device. This really is due to its enhanced options and suppleness which makes it the most effective platform for mobile development. http://tinyurl.com/q34h95o

  • Android Application Development Said:

    Thanks for sharing such a informative post android app development Is used for creating new and wonderful apps for android OS and it is now on demand because of its wonderful feature. http://www.mobilepundits.com/Outsource_Android_Development.html

  • John Said:

    I found perfect site for creating apps...Yesterday I ended up on some site called apps-machine.com . I have to share it with you guys. I started creating my own app and after 15 minutes clicking on their control panel(no programming,just clicks) I made app in what user could make effects on their photos,paint photos,play music,play videos,have notepad,chat and stream music. They got literally 1000's of features on their control panel :D I think this could be a gold mine :P :P And I read something that they have free app development and so on. Aaand you can change everything all the backgrounds,colors,tabs...and you instantly see it on that same page through their simulator..don't know how they managed to do that but it is super handy...I am super excited at the moment..time to get some apps on apple and play store :D :D

  • Himanshu Patel Said:

    Hi, Greetings from NectarBits(Creative Apps Devs.) !!!  We are a custom Mobile Application development company treating onto the platform of iPhone and Android.  We would definitely go ahead with your project. Please send us the project details on  Email:-himanshu@nectarbits.com  Skype ::- jaks1113 Thanks and Regards,  Himanshu Patel NectarBits(Creative Apps Devs.) www.nectarbits.com

  • Hiamnshu Patel Said:

    Hi Guys., Greetings from NectarBits(Creative Apps Development Company) is a Mobile Application Experts Company providing Quality Mobile Apps treating onto platform of Best Apps Developed in IOS and Android. Let us know if we can help you with Our Quality Application Development Services Willing to Hoping to hear from you soon.  Email;-himanshu@nectarbits.com Thanks and Regards , Himanshu Patel

  • basit ali Said:

    great efforts....... best for biggeners

  • Hyperlink Infosystem Said:

    Android Application Development in India is one of the hottest topics these days because of the incredibly lucrative Android Market. The increasing influx of people especially from Western countries look for software solutions that are not only budget safe but also goal reaching. Hyperlink Infosystem provides many solutions to meet these kinds of requirements. http://www.hyperlinkinfosystem.com/


Who we are ?

The Linux Foundation is a non-profit consortium dedicated to the growth of Linux.

More About the foundation...

Frequent Questions

Join / Linux Training / Board