Wednesday, January 2, 2013

How To Create A Relative Layout With A Background Image

Most of the example in these Android tutorial use Linear Layout as it is the default layout. This type of layout has its advantages and disadvantages. If you would like to use a background image using a Linear Layout, you can use the attribute android:background to accomplish this. However, this attribute has its limitations. The most common one is that the image being used stretches and can distort the image. To get around this, using a Relative Layout and Image View would be the best solution.

In a previous post, it describes how to create a button on your Android application. This tutorial will modify the code in the mentioned button tutorial. And it just involves modifying the main.xml file.

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout     	xmlns:android="http://schemas.android.com/apk/res/android"    	android:layout_width="fill_parent"	android:layout_height="fill_parent">     <ImageView        android:id="@+id/BackImage"        android:layout_width="wrap_content"        android:layout_centerInParent="true"        android:layout_height="wrap_content"	android:scaleType="fitXY"	android:gravity="top"	android:background="@android:drawable/ic_btn_speak_now" >    </ImageView> 	<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"	    android:layout_width="fill_parent"	    android:layout_height="fill_parent"	    android:orientation="vertical"	    android:layout_alignParentTop="true" > 	    <TextView	        android:layout_width="fill_parent"	        android:layout_height="wrap_content"	        android:text="@string/hello" /> 	    <Button	    android:layout_width="wrap_content"	    android:layout_height="wrap_content"	    android:text="@string/button_text" 	    android:onClick="sendMessage" /> 	    <ImageButton	    android:layout_width="wrap_content"	    android:layout_height="wrap_content"	    android:src="@drawable/ic_launcher"	    android:onClick="sendQuestion" />     	    <Button	    android:layout_width="wrap_content"	    android:layout_height="wrap_content"	    android:text="@string/button_text"	    android:drawableLeft="@drawable/ic_launcher"	    android:onClick="sendGoodbye"/> 	</LinearLayout></RelativeLayout>

As seen from the code above, the modifications are self-explanatory. The RelativeLayout tag is added with its basic attributes and the ImageView tag is also added with its attributes. One thing that should be noted though is the LinearLayout attribute android:layout_alignParentTop="true". This aligns the LinearLayout view right on top of the ImageView. The Parent of the LinearLayout would be the RelativeLayout.

Related Posts:

Tags: android tutorial


Source : htmlpress[dot]net

0 comments:

Post a Comment