Saturday, March 30, 2013

Android Relative Layouts

This post briefly describes how to use Android Relative Layouts.

1. Why Use Relative Layouts?

One of the challenges when it comes to designing Android apps is making your app look presentable on a multitude of different Android devices with different screen sizes and resolutions. Relative layouts can help to place views in the proper locations without specifying an absolute position.



2. Bottom Toolbar

For example, you can use a relative layout to create toolbar that will always appear at the bottom of the screen. The following is a screenshot of the same layout with in the layout editor with two differently sized devices being simulated. Notice that the toolbar stays in the same location at the bottom of the app.

The layout on small sized device.


The layout on large sized tablet.

Listed below is the xml for the layout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_height="fill_parent" android:id="@+id/relativeLayout1"
 android:layout_width="fill_parent">

 <ImageView android:id="@+id/imageView1"
  android:layout_height="wrap_content" android:layout_width="wrap_content"
  android:layout_alignParentBottom="true" android:src="@drawable/bottomtoolbar"
  android:layout_centerHorizontal="true"></ImageView>
  
</RelativeLayout>


3. Positioning a Second Toolbar

You can also use the relative layout to position a second detail toolbar directly above the bottom toolbar. You do this by specifying that the detail toolbar is position directly above the bottom toolbar. You do this by adding the following attribute to the second ImageView tag.

android:layout_above="@+id/imageView1"


A screenshot of the layout with the second toolbar added.


4. Full Layout XML

Listed below is the full layout XML for this tutorial.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_height="fill_parent" android:id="@+id/relativeLayout1"
 android:layout_width="fill_parent">

 <ImageView android:id="@+id/imageView1"
  android:layout_height="wrap_content" android:layout_width="wrap_content"
  android:layout_alignParentBottom="true" android:src="@drawable/bottomtoolbar"
  android:layout_centerHorizontal="true"></ImageView>
 <ImageView android:id="@+id/imageView2"
  android:layout_height="wrap_content" android:layout_width="wrap_content"
  android:layout_above="@+id/imageView1" android:src="@drawable/detailtoolbar"
  android:layout_centerHorizontal="true"></ImageView>

</RelativeLayout>


Thanks for reading the tutorial!

1 comment:

  1. Please continue this great work and I look forward to more of your awesome blog posts. 9apps games

    ReplyDelete