Android Madness

What is an Android ?

Android is a software stack for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.

Android is an operating system based on Linux with a Java programming interface. It provides tools, e.g. a compiler, debugger and a device emulator as well as its own Java Virtual machine (Dalvik Virtual Machine - DVM). Android is created by the Open Handset Alliance which is lead by Google.
Android uses a special virtual machine, e.g. the Dalvik Virtual Machine. Dalvik uses special bytecode. Therefore you cannot run standard Java bytecode on Android. Android provides a tool "dx" which allows to convert Java Class files into "dex" (Dalvik Executable) files. Android applications are packed into an .apk (Android Package) file by the program "aapt" (Android Asset Packaging Tool) To simplify development Google provides the Android Development Tools (ADT) for Eclipse . The ADT performs automatically the conversion from class to dex files and creates the apk during deployment.
Android supports 2-D and 3-D graphics using the OpenGL libraries and supports data storage in a SQLitedatabase.
Every Android applications runs in its own process and under its own userid which is generated automatically by the Android system during deployment. Therefore the application is isolated from other running applications and a misbehaving application cannot easily harm other Android applications.


What is an Open Handset Alliance ?

The Open Handset Alliance (OHA) is a business alliance of 84 firms to develop open standards for mobile devices.
The OHA was established on 5 November 2007, led by Google with 34 members including mobile handset makers, application developers, some mobile carriers and chip makers. Android, the flagship software of the alliance, is based on an open source license. 
Members of OHA can be found on this link.


What does Android have that others don't ?
  • Google Map applications
  • Background services and applications
  • Shared data and interprocess communication

What is an Android SDK ?

The Android software development kit (SDK) includes everything that need to start developing, testing and debugging Android applications.
SDK includes :
  • Android API's : They provide developer access to the Android Stack.
  • Development Tools : These allow us to compile and debug android applications
  • Android Virtual Machine (AVD) Manager and Emulator : The Android Emulator is a fully interactive Android device emulator featuring several alternatives skins. The emulator runs within an Android Virtual Device that simulates the device hardware configuration.
  • Full documentation : SDK includes extensive code - level reference information detailing exactly what's included in each package and class and how to use them.

Android Software Stack

Android software stack is composed of the elements shown in figure 1-1


                                                                         Figure 1-1

Applications
Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are written using the Java programming language.

Application Framework
Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are written using the Java programming language.
By providing an open development platform, Android offers developers the ability to build extremely rich and innovative applications. Developers are free to take advantage of the device hardware, access location information, run background services, set alarms, add notifications to the status bar, and much, much more.
Developers have full access to the same framework APIs used by the core applications. The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities (subject to security constraints enforced by the framework). This same mechanism allows components to be replaced by the user.
Underlying all applications is a set of services and systems, including:
  • A rich and extensible set of Views that can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser
  • Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data
  • A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files
  • Notification Manager that enables all applications to display custom alerts in the status bar
  • An Activity Manager that manages the lifecycle of applications and provides a common navigation backstack
Libraries
Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework. Some of the core libraries are listed below:
  • System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices
  • Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG
  • Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications
  • LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view
  • SGL - the underlying 2D graphics engine
  • 3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software rasterizer
  • FreeType - bitmap and vector font rendering
  • SQLite - a powerful and lightweight relational database engine available to all applications
Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.
Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool.
Linux Kernel
The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management.
Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.


Important Android components
An Android application consists out of the following parts:
  • Activity - Represents the presentation layer of an Android application, e.g. a screen which the user sees. An Android application can have several activities and it can be switched between them during runtime of the application.
  • Views - The User interface of an Activities is build with widgets classes which inherent from "android.view.View". The layout of the views is managed by android.view.ViewGroups".
  • Services - perform background tasks without providing an UI. They can notify the user via the notification framework in Android.
  • Content Provider - provides data to applications, via a content provider your application can share data with other applications. Android contains a SQLite DB which can serve as data provider
  • Intents are asynchronous messages which allow the application to request functionality from other services or activities. An application can call directly a service or activity (explicit intent) or ask the Android system for registered services and applications for an intent (implicit intents). For example the application could ask via an intent for a contact application. Application register themself to an intent via an IntentFilter. Intents are a powerful concept as they allow to create loosely coupled applications.
  • Broadcast Receiver - receives system messages and implicit intents, can be used to react to changed conditions in the system. An application can register as a broadcast receiver for certain events and can be started if such an event occurs.
Other Android parts are Android Widgets or Live Folders and Live Wallpapers . Live Folders display any source of data on the homescreen without launching the corresponding application.


Programming languages used in Android
  • At launch, Java was the only officially supported programming language for building distributable third-party Android software.
  • Android Native Development Kit (Android NDK) which will allow developers to build Android software components with C and C++
  • In addition to delivering support for native code, Google is also extending Android to support popular dynamic scripting languages. Earlier this month, Google launched the Android Scripting Environment (ASE) which allows third-party developers to build simple Android applications with Perl, JRuby, Python, LUA and BeanShell. For having idea and usage of ASE, refer this Example link.
  • Scala is also supported. For having examples of Scala, refer these Example link-1 Example link-2 Example link-3 .


Installation of Android


This tutorial shows you how to download and install Android SDK to get you started developing Android applications.
The objective of this android  tutorial would be
a) Install the Android SDK on Windows  and configure with eclipse
b) Create an Application that Runs on the Android Emulator
1.Install Java (if it is not on your machine)

Click on Download JDK button

Select Platform and Language for your download and click on license Agreement checkbox  
Click on continue button. Then

Click on jdk-6u23-windows-i586.exe for download
Now save file and install the jdk.
2. Install Eclipse
Eclipse is a professional editor.

Go to http://www.eclipse.org/downloads/ . Click on Windows 32 Bit from the right side download icon of Eclipse IDE for Java Developers row.

Click on download icon.
After it has finished downloading, you will have this file in your directory. Unzip this file.

Now you find the eclipse.exe file from your unzip folder directory and double-click on the file eclipse.exe to run Eclipse editor. You will see this.
Click ok.
2.1. Install the ADT Plug-in
  • · Start Eclipse, then select Help > Software Updates or Help>Install New Software…. In the dialog that appears, click the Available Software/Install New Software tab.
  • · Click Add Site.
  • · In the Add Site dialog that appears,

Copy and paste this link into input box “Location/Work with”: https://dl-ssl.google.com/android/eclipse/
Back in the Available Software view, you should see the plugin. “Android Developer Tools”, and “Android Editors” should both be checked. The Android Editors feature is optional, but recommended. Then click on the button “Install …”
Click on the button next
Check the “I accept the terms of the license agreements” and click Finish.
Eclipse will ask to restart, click on the button Yes.
After restart, update your Eclipse preferences to point to the SDK directory:
If you want to know more then go to  http://developer.android.com/sdk/eclipse-adt.html and read the content Downloading the ADT Plugin

2.2. Android SDK


Download the Android SDK from the Android homepage under Android SDK download . The download contains a zip file which you can extract to any place in your file system, e.g. I placed it under “c:\android” .

2.3. Configuration

In Eclipse open the Preferences dialog via Windows -> Preferences. Select Android and maintain the installation path of the Android SDK. Click Apply, then OK.
Now, set your PATH environment variable by right click on My Computer, and select Properties. Under the Advanced tab, hit the Environment Variables button, and in the dialog that comes up, double-click on Path under System Variables. Add the full path to the tools/ directory to the path, in this case, it is: ;C:\android\android-sdk-windows\tools. Then click OK , OK , OK.
2.4.Create an AVD
In this tutorial, you will run your application in the Android Emulator. Before you can launch the emulator, you must create an Android Virtual Device (AVD). An AVD defines the system image and device settings used by the emulator.
To create an AVD:
In Eclipse, choose Window > Android SDK and AVD Manager.

2.3. Configuration


In Eclipse open the Preferences dialog via Windows -> Preferences. Select Android and maintain the installation path of the Android SDK. Click Apply, then OK.
Now, set your PATH environment variable by right click on My Computer, and select Properties. Under the Advanced tab, hit the Environment Variables button, and in the dialog that comes up, double-click on Path under System Variables. Add the full path to the tools/ directory to the path, in this case, it is: ;C:\android\android-sdk-windows\tools. Then click OK , OK , OK.
2.4.Create an AVD
In this tutorial, you will run your application in the Android Emulator. Before you can launch the emulator, you must create an Android Virtual Device (AVD). An AVD defines the system image and device settings used by the emulator.
To create an AVD:

In Eclipse, choose Window > Android SDK and AVD Manager.
  1. Select Virtual Devices in the left panel.
  2. Click New.
The Create New AVD dialog appears.
3. Type the name of the AVD, such as “testAVD”.

4. Choose a target. The target is the platform (that is, the version of the Android SDK, such as 2.2) you want to run on the emulator.
5. Click Create AVD.  Your new AVD is created now!
Create a New Android Project
After you’ve created an AVD, the next step is to start a new Android project in Eclipse.
  1. From Eclipse, select Select File -> New -> Other…

Click on Android Project and click Next.
2. Fill in the project details with the following values:
  1. Project name: HelloAndroid
  2. Application name: Hello, Android
  3. Package name: com.droidbd.helloandroid (or your own private namespace)
4. Create Activity: HelloAndroid
5.  Min SDK version :        8 (as per API level)
Click Finish.
Run the Application
The Eclipse  plug-in makes it easy to run your applications:
  1. Select Run > Run.
Or Right click on project from project explorer and go
Run as ->Android Application
Yeah, you will see a black screen at your AVD with Your application name and a “Hello …..” text.


The Structure of an Android Project 

After you create a new project in eclipse, you will see the following top-level folders in your package explorer.
                                                                      Figure 1-2

Each of them in detail:

  • /src : This folder will contain the java source files. In the screenshot(figure 1-3) you can see 'activity' file created in a sample project. The files in this folder will be organized according to the package.
                                                                      Figure 1-3
  • /gen : This is also a source folder, but will be contain Java source files that will be automatically generated by the android platform. Notable among the generated Java files is the R class, which you see in the screenshot. The framework will generate R class file and you can read more about it in the android documentation.
                                                                      Figure 1-4

  • /res : This directory contains all the external resources (images, data files etc) that are used by the android application. These external resources (content) will be referenced in the android application.This contains the following sub-folders

  1. /res/drawable
  2. /res/layout
  3. /res/values
                                                                     Figure 1-5

      1. /res/drawable : This folder contains all images, pictures etc. If you want to include an                                                                                     image or an icon in your android application, then you will be placing it in this folder.
       2. /res/layout : This folder contains the UI layouts that will be used in the project. These UI layouts are stored as XML files. You can read more about the UI layouts in the android documentation.
      3. /res/values : This folder again contains XML files, which contain key values pairs that will be referenced in the application. These XML files declare Arrays, colors, dimensions, strings etc. The main idea of having these values in a separate XML file is that the values can be used based on the locale without actually changing the source code. For example the messages in the application can be in different languages based on the use locale.
      4. /assets : This folder also contains external resources used in the application like the /res folder. But the main difference is that the resources are stored in raw format and can be read only programmatically.

Android Manifest File : An Android application is described the file "AndroidManifest.xml". This file will declare all activities, services, broadcast receivers and content provider of the application. It will also contain the required permissions for the application. For example if the application requires network access it must be specified here. "AndroidManifest.xml" can be thought as the deployment descriptor for an Android application.
                                                                                Figure 1-6
The "package" attribute defines the base package for the following Java elements. It is also unique as the Android Marketplace only allows application for a specfic package once. Therefore a good habit is to use your reverse domain name as a package to avoid collisions with other developers.
"android:versionName" and "android:versionCode" specify the version of your application. "versionName" is what the user sees and can be any string. "versionCode" must be an integer and the Android Market uses this to determine if you provided a newer version to trigger the update on devices which have your application installed. You typically start with "1" and increase this value by one if you roll-out a new version of your application.
"activity" defines an activity in this example pointing to the class "CelFahConverterActivity". For this class an intent filter is registered which defines that this activity is started once the application starts (action android:name="android.intent.action.MAIN"). The category definition (category android:name="android.intent.category.LAUNCHER" ) defines that this application is added to the application directory on the Android device. The @ values refer to resource files which contain the actual values. This makes it easy to provide different resources, e.g. strings, colors, icons, for different devices and makes it easy to translate applications.
The "uses-sdk" part of the "AndroidManifest.xml" defines the minimal SDK version your application is valid for. This will prevent your application being installed on devices with older SDK versions.


Installation of Android without internet :

Requiremets :
  • A friend or any person who is already having android setup in his/her laptop/computer
  • A device (may be a pendrive or a hard disk etc) to transfer files
Steps : 
  1. Copy Android sdk from your friends laptop/computer
  2. If you dont have eclipse with you, copy even whole eclipse folder (with ADT plugin)
  3. Copy these two files in your laptop/computer in a "C" preferably
  4. Then open eclipse 
  5. Go to windows->preferences->Android , then give path SDK location
And you are done.











Android LifeCycle :


The life cycle is shown diagrammatically below



Your activity monitors and reacts to these events by instantiating methods that override the Activity class methods for each event:

onCreate
Called when your activity is first created. This is the place you normally create your views, open any persistent datafiles your activity needs to use, and in general initialize your activity. When calling onCreate, the Android framework is passed a Bundle object that contains any activity state saved from when the activity ran before.

onStart
Called just before your activity becomes visible on the screen. Once onStart completes, if your activity can become the foreground activity on the screen, control will transfer to onResume. If the activity cannot become the foreground activity for some reason, control transfers to the onStopmethod.

onResume
Called right after onStart if your activity is the foreground activity on the screen. At this point your activity is running and interacting with the user. You are receiving keyboard and touch inputs, and the screen is displaying your user interface. onResume is also called if your activity loses the foreground to another activity, and that activity eventually exits, popping your activity back to the foreground. This is where your activity would start (or resume) doing things that are needed to update the user interface (receiving location updates or running an animation, for example).

onPause
Called when Android is just about to resume a different activity, giving that activity the foreground. At this point your activity will no longer have access to the screen, so you should stop doing things that consume battery and CPU cycles unnecessarily. If you are running an animation, no one is going to be able to see it, so you might as well suspend it until you get the screen back. Your activity needs to take advantage of this method to store any state that you will need in case your activity gains the foreground again—and it is not guaranteed that your activity will resume. If the mobile device you are running on runs out of memory, there is no virtual memory on disk to use for expansion, so your activity may have to make way for a system process that needs memory. Once you exit this method, Android may kill your activity at any time without returning control to you.

onStop
Called when your activity is no longer visible, either because another activity has taken the foreground or because your activity is being destroyed.

onDestroy
The last chance for your activity to do any processing before it is destroyed. Normally you'd get to this point because the activity is done and the framework called its finish method. But as mentioned earlier, the method might be called because Android has decided it needs the resources your activity is consuming.
It is important to take advantage of these methods to provide the best user experience possible. 


All of these are hooks that you can override to do appropriate work when the activity changes state. All activities will implement onCreate(Bundle) to do their initial setup; many will also implement onPause() to commit changes to data and otherwise prepare to stop interacting with the user. You should always call up to your superclass when implementing these methods.
 public class Activity extends ApplicationContext {
     protected void onCreate(Bundle savedInstanceState);

     protected void onStart();

     protected void onRestart();

     protected void onResume();

     protected void onPause();

     protected void onStop();

     protected void onDestroy();
 }

Here is the short program which gives more idea about android life cycle :


package com.sujith.interest;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class LifeCycleActivity extends Activity {

private final static String TAG="LifeCycleActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG,"On Create");
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i(TAG,"On Destroy");
}

@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.i(TAG,"On Pause");
}

@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.i(TAG,"On Restart");
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i(TAG,"On Resume");
}

@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.i(TAG,"On Start");
}

@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.i(TAG,"On Stop");
}
}

After running the above code , you will get following screen.




To see logcat message click DDMS from right top of eclipse click LogCat View .

You will get a screen like this.



Android Development Tool (ADT) in Detail 

The Android SDK includes several tools and utilities to help you to create, test, and debug your projects. ADT plug-in conveniently incorporates most of those tools into the eclipse IDE, where you can access them from the DDMS (Dalvik Debug Monitoring Service) perspective, including:
  • The Android SDK and Virtual Device Manager : Used to create and manage Android Virtual Devices
    (AVD) and SDK packages. The AVD hosts an emulator running a particular build of Android, letting you specify the supported SDK version, screen resolution, amount of SD card storage available hardware capabilities.
  • The Android Emulator : An implementation of the Android Virtual machine designed to run within a virtual device on your development computer. Use the emulator to test and debug your android applications.
  • Dalvik Debug Monitoring service (DDMS) : Use the DDMS perspective to monitor and control the Dalvik virtual machines on which you are debugging your applications.
  • Android Asset Packaging Tool : Constructs the distributable Android package files  
  • Android Debug Bridge (ADB) : A client - server application that provides a link to a running emulator. It lets you copy files, install compiled application packages (.apk), and run shell commands.
The following additional tools are also available :
  • SQLite3 : A database tool that you can use to access the SQLite database files created and used by android.
  • Traceview : A graphical analysis tool for viewing the trace logs from your Android application.
  • MkSDCard : Creates an SD card disk image that can be used by the emulator to simulate an external storage card.
  • Dx : Converts java .class bytecode into Android .dex bytecode.
  • activityCreator : A script that builds Ant build files that you can use to compile your Android applications without ADT plug - in.
  • layoutOpt : A tool that analyses your layout resources and suggests improvements and optimization.



Android - What does android application contain ?

Android application consists of loosely coupled components, bound by the application manifest. This manifest file will describe about each component and how they all interact, as well as the application metadata including its hardware and platform requirements. For example :

Building blocks of android application are :
  • Activities : It is the presentation layer. Every screen of your application will be an extension of the Activity Class.
  • Services : The invisible workers of your application are called services. Service components run in the background, updating your data sources and visible Activities and triggering notifications. These services are used to perform regular processing that needs to continue even when your application's activities aren't active or visible.
  • Content Providers : Share-able data stores. They are preferred mean of sharing data across application boundaries. You can configure your content own content providers to permit access from other applications and use content providers exposed by other applications to access their stored data.
  • Intent : An inter application message - passing framework. Using Intents you can broadcast messages system - wide or to a target Activity or Service.
  • Broadcast Receivers : Intent broadcast consumers. If you create and register a Broadcast Receiver, your application can listen for broadcast Intents that match specific filter criteria. Broadcast Receivers will automatically start your application to respond to an incoming Intent, making them perfect for creating event - driven applications.
  • Notifications : A user notification framework. Notifications let you signal users without stealing focus or interrupting  their current activities. 


Android - What are Views, Layouts?

This class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.). The ViewGroup subclass is the base class for layouts, which are invisible containers that hold other Views (or other ViewGroups) and define their layout properties.

Using Views

All of the views in a window are arranged in a single tree. You can add views either from code or by specifying a tree of views in one or more XML layout files. There are many specialized subclasses of views that act as controls or are capable of displaying text, images, or other content.
Once you have created a tree of views, there are typically a few types of common operations you may wish to perform:
  • Set properties: for example setting the text of a TextView. The available properties and the methods that set them will vary among the different subclasses of views. Note that properties that are known at build time can be set in the XML layout files.
  • Set focus: The framework will handled moving focus in response to user input. To force focus to a specific view, call requestFocus().
  • Set up listeners: Views allow clients to set listeners that will be notified when something interesting happens to the view. For example, all views will let you set a listener to be notified when the view gains or loses focus. You can register such a listener using setOnFocusChangeListener(android.view.View.OnFocusChangeListener). Other view subclasses offer more specialized listeners. For example, a Button exposes a listener to notify clients when the button is clicked.
  • Set visibility: You can hide or show views using setVisibility(int) .


Layouts 


View Group
A ViewGroup is a special view that can contain other views (called children.) The view group is the base class for layouts and views containers. This class also defines the ViewGroup.LayoutParams class which serves as the base class for layouts parameters.

Layout 

Your layout is the architecture for the user interface in an Activity. It defines the layout structure and holds all the elements that appear to the user. You can declare your layout in two ways:
  • Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.
  • Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and manipulate their properties) programmatically.


The six different layouts are
1. Linear Layout
2. Relative Layout
3. Table Layout
4. Grid View
5. Tab Layout
6. List View
Android allows you to create view layouts using simple XML file. All the layouts must be placed in /res/layout folder.

Android Layout Directory

Mostly in many applications we use “Linear Layout” and “relative layout” only. So we will learn these layouts below.

Linear Layout

In a linear layout, like the name suggests, all the elements are displayed in a linear fashion, either Horizontally or Vertically and this behavior is set in android:orientation which is an attribute of the node LinearLayout.
i.e.
Example of Vertical layout
1
<LinearLayout android:orientation="vertical"> .... </LinearLayout>

Example of Horizontal layout
1
<LinearLayout android:orientation="horizontal"> .... </LinearLayout>
Let’s create project:
1) Create a new project File -> New -> Android Project
2) Create linear_layout.xml in res/layout and insert following
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="utf-8"?>

  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Email:" />
  <EditText android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>            
  <Button android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Login"/>
 <LinearLayout android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:background="#2a2a2a"
            android:layout_marginTop="10dp">
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Home"
            android:gravity="center"/>
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="About"
            android:paddingLeft="8dp"
            android:gravity="center"/>  
  </LinearLayout>
</LinearLayout>


Linear Layout Output
Here Email TextView, EditText and Login Button are vertical in layout. whereas Home and about are in horizontal layout.

Relative Layout

In a relative layout every element arranges itself relative to other elements or a parent element.

Relative To Container

These properties will layout elements relative to the parent container.
1) android:layout_alignParentBottom – Places the bottom of the element on the bottom of the container
2) android:layout_alignParentLeft – Places the left of the element on the left side of the container
3) android:layout_alignParentRight – Places the right of the element on the right side of the container
4) android:layout_alignParentTop – Places the element at the top of the container
5) android:layout_centerHorizontal – Centers the element horizontally within its parent container
6) android:layout_centerInParent – Centers the element both horizontally and vertically within its container
7) android:layout_centerVertical – Centers the element vertically within its parent container

Example


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    <Button
        android:id="@+id/button01"
        android:text="Top Button Horizontally center"
        android:layout_alignParentTop="true"
        android:layout_width="wrap_content"
        android:textSize="10sp"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/button02"
        android:text="Bottom Button Horizontally center"
        android:layout_alignParentBottom="true"
        android:layout_width="wrap_content"
        android:textSize="10sp"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/button03"
        android:text="Left Button Vertically center"
        android:layout_width="wrap_content"
        android:textSize="10sp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_height="wrap_content" /> 
<Button
        android:id="@+id/button04"
        android:text="Right Button Vertically center"
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:textSize="10sp"
        android:layout_height="wrap_content" />
</RelativeLayout>


Relative Layout Output-1

Relative To Other Elements

These properties allow you to layout elements relative to other elements on screen.
1) android:layout_above – Places the element above the specified element
2) android:layout_below – Places the element below the specified element
3) android:layout_toLeftOf – Places the element to the left of the specified element
4) android:layout_toRightOf – Places the element to the right of the specified element

Example


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    <Button
        android:id="@+id/button01"
        android:text="Button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/button02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/button01"
        android:layout_marginLeft="8dp"
        android:text="To the RightOf Button1"/>
    <Button
        android:id="@+id/button03"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/button01"
        android:layout_alignParentRight="true"
        android:text="Button 2"/>
    <Button
        android:id="@+id/button04"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/button01"
        android:layout_toLeftOf="@id/button03"
        android:text="To Left of Button 2"/>
</RelativeLayout>


Relative Layout output-2

Alignment With Other Elements

These Properties allow you to specify how elements are aligned in relation to other elements.
1) android:layout_alignBaseline – Aligns baseline of the new element with the baseline of the specified element
2) android:layout_alignBottom – Aligns the bottom of new element in with the bottom of the specified element
3) android:layout_alignLeft – Aligns left edge of the new element with the left edge of the specified element
4) android:layout_alignRight – Aligns right edge of the new element with the right edge of the specified element
5) android:layout_alignTop – Places top of the new element in alignment with the top of the specified element

Example


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    <Button
        android:id="@+id/button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button-2 right boundary aligned with this button"/>
    <Button
        android:id="@+id/button02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button-2"
        android:layout_below="@id/button01"
        android:layout_alignRight="@+id/button01"/>
</RelativeLayout>

Comments

Popular posts from this blog

EJB - Stateful vs Stateless

Inversion of Control vs Dependency Injection