Вы находитесь на странице: 1из 32

Android Application Development Training Tutorial

For more info visit http://www.zybotech.in

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Chapter-1 Quick start


Android combines the ubiquity of cell phones, the excitement of open source software, and the corporate backing of Google and other Open Handset Alliance members like Intel, TI, T-Mobile, and NTT DoCoMo. Luckily, getting started developing with Android is easy. You dont even need access to an Android phonejust a computer where you can install the Android SDK and phone emulator.

Installing the Tools


The Android software development kit (SDK) works on Windows, Linux, and Mac OS X. The applications you create, of course, can be deployed on any Android devices. Before you start coding, you need to install Java, an IDE, and the Android SDK. Java 5.0+ First you need a copy of Java. All the Android development tools require it, and programs you write will be using the Java language. JDK 5 or 6 is required. Its not enough to just have a runtime environment (JRE); you need the full development kit. I recommend getting the latest Sun JDK 6.0 update from the Sun download site.1 Mac OS X users should get the latest version of Mac OS X and the JDK from the Apple website. To verify you have the right version, run this command from your shell window. Heres what I get when I run it: C:\> java -version java version "1.6.0_13" Java(TM) SE Runtime Environment (build 1.6.0_13-b03) Java HotSpot(TM) Client VM (build 11.3-b02, mixed mode, sharing) Eclipse Next, you should install a Java development environment if you dont have one already. I recommend Eclipse, because its free and because its used and supported by the Google developers who created Android. The minimum version of Eclipse is 3.3.1, but you should always use whatever is the most up-to-date production version. Note that you need more than just the standard Eclipse SDK classic platform. Go to the Eclipse downloads and pick Eclipse IDE for Java Developers. Follow the directions there for downloading, unpacking, and installing Eclipse into a suitable location (like C:\Eclipse on Windows). Android Next, download the latest Android SDK from Google. The Android download has packages for Windows, Mac OS X, and Linux. After downloading the package thats right for you, unpack the .zip file to a convenient directory (for example, C:\Google). By default, the SDK will be expanded into a subdirectory like androidsdk- windows1.5_r2. This is your SDK install directory; make a note of the full path so you can refer to it later.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Fig1.1 Installing the Android Development Toolkit No special install program is needed but I do recommend you add the SDKs bin directory to your PATH. The next step is to start Eclipse and configure it . Eclipse Plug-In To make development easier, Google has written a plug-in for Eclipse called the Android Development Toolkit (ADT). To install the plug-in, follow these steps (note these directions are for Eclipse 3.4different versions may have slightly different menus and options): 1. Start Eclipse, and select Help > Software Updates.... 2. Click the Available Software tab if its not already selected. 3. Click the Add Site... button. 4. Enter the location of the Android update site: https://dl-ssl.google. com/android/eclipse/. If you have trouble with this address, try using http in the location instead of https. Once youve filled it out, the dialog box should look like Figure 1.1.Click OK. 5. The Android site should now appear in the Available Software view. Select the checkbox next to it, and then click Install.... If you get an error message, then you may not have the right version of Eclipse. I strongly recommend using either the prebuilt Eclipse IDE for Java or the Eclipse IDE for Java EE Development packages, version 3.4 or newer. If you have a custom install of Eclipse, then to use the Android editors you will also need to install the Web Standard Tools (WST) plug-in and all its prerequisites. See the Web Tools platform home page5 for more details and download links. These are already built into the recommended packages mentioned earlier. 6. Click Next, accept the license agreements, and then click Finish to start the download and install process. 7. Once the install is done, restart Eclipse. 8. When Eclipse comes back up, you may see a few error messages because you need to tell it where the Android SDK is located. Select Window > Preferences > Android (Eclipse > Preferences on Mac OS X),(and enter the SDK install directory you noted earlier. Click OK. Whew! Luckily, you have to do that only once (or at least once every time a new version of ADT or Eclipse comes out). Now that everything is installed, its time to write your first program.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Chapter-2
Getting to Know Android

Why Android?
Googles Android mobile phone software platform may be the next big opportunity for application software developers. Google announced the Open Handset Alliance and the Android platform in 5th November of 2007, releasing the first beta version of the Android Software Development Kit (SDK) at the same time. In the United States, T-Mobile announced the G1 Android mobile phone in October of 2008, and estimates are that several hundred thousand G1s were sold before the end of that year. There are already several competing mobile phone software stacks in the market, so why is there such interest in Android? Android has the potential for removing the barriers to success in the development and sale of a new generation of mobile phone application software. Just as the standardized PC and Macintosh platforms created markets for desktop and
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

server software, Android, by providing a standard mobile phone application environment, will create a market for mobile applicationsand the opportunity for applications developers to profit from those applications.

Why is Android important?


The computer technology press has lavished attention on Android since its announcement and initial SDK release. Android is important as a platform for two disparate, yet compelling, reasons, among many others. Android is a market-mover. The mobile-application space is crowded and difficult to gain footing for a newcomer. Google has the resources and the mind-share to make a splash in any market it puts in its sights. Google's entry into the mobile space has been in the works for a few years. Android was a separate and distinct company purchased by Google to give it a jump-start on a mobile presence. Anything Google is doing gets attention, and publicity is good for introducing new platforms. Score one for Android. The second reason Android is important is because of its application model. Android Applications are not monolithic, menu-laden applications that require a great deal of clicking and tapping to operate.

The Future
Android sits alongside a new wave of mobile operating systems designed for increasingly powerful mobile hardware. Windows Mobile and Apples iPhone now provide a richer, simplified development environment for mobile applications. However, unlike Android, theyre built on proprietary operating systems that often prioritize native applications over those created by third parties and restrict communication among applications and native phone data. Android offers new possibilities for mobile applications by offering an open development environment built on an open source Linux kernel. Hardware access is available to all applications through a series of API libraries, and application interaction, while carefully controlled, is fully supported. In Android, all applications have equal standing. Third-party and native Android applications are Written using the same APIs and are executed on the same run time. Users can remove and replace any native application with a third-party developer alternative; even the dialer and home screens can be replaced.

Android SDK Features


The true appeal of Android as a development environment lies in the APIs it provides. As an application-neutral platform, Android gives you the opportunity to create applications that are as much a part of the phone as anything provided out of the box. The following list highlights some of the most noteworthy Android features: No licensing, distribution, or development fees Wi-Fi hardware access GSM, EDGE, and 3G networks for telephony or data transfer, allowing you to make or receive calls or SMS messages, or to send and retrieve data across mobile networks Comprehensive APIs for location-based services such as GPS Full multimedia hardware control including playback and recording using the camera and Microphone APIs for accelerometer and compass hardware IPC message passing
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Shared data stores an integrated open source Webkit-based browser Full support for applications that integrate Map controls as part of their user interface Peer-to-peer (P2P) support using Google Talk Mobile-optimized hardware-accelerated graphics including a path-based 2D graphics library and support for 3D graphics using OpenGL ES

Introducing the Open Handset Alliance


The Open Handset Alliance (OHA) is a collection of more than 77 technology companies including hardware manufacturers, mobile carriers, and software developers. Of particular note are the prominent mobile technology companies Motorola, HTC, T-Mobile, and Qualcomm. In their own words, the OHA represents: A commitment to openness, a shared vision for the future, and concrete plans to make the vision a reality. To accelerate innovation in mobile and offer consumers a richer, less expensive, and better mobile experience.
http://www.openhandsetalliance.com/oha_faq.html

The OHA hopes to deliver a better mobile software experience for consumers by providing the platform needed for innovative mobile development at a faster rate and a higher quality without licensing fees for software developers or handset manufacturers. Ultimately the success of Android as a mobile platform will depend largely on the success of OHA partners in releasing desirable handsets and mobile services that encourage the widespread adoption of Android phones. Developers meanwhile have the opportunity to create innovative new mobile applications for Android to encourage more mobile technology companies to become part of the OHA.

Android Development Tools


The Android SDK includes several tools and utilities to help you create, test, and debug your projects. A detailed examination of each developer tool is outside the scope of this book, but its worth briefly reviewing whats available. For more detail than is included here, check out the Android documentation at: http://code.google.com/android/intro/tools.html As mentioned earlier, the ADT plug-in conveniently incorporates most of these tools into the Eclipse IDE, where you can access them from the DDMS perspective, including: The Android Emulator An implementation of the Android virtual machine designed to run on your development computer. You can 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 youre debugging your applications. Android Asset Packaging Tool (AAPT) Constructs the distributable Android package files (.apk). Android Debug Bridge (ADB) The ADB is 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 Graphical analysis tool for viewing the trace logs from your Android application MkSDCard Creates an SDCard disk image that can be used by the emulator to simulate an
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

External storage card. dx Converts Java .class bytecode into Android .dex bytecode. activityCreator Script that builds Ant build files that you can then use to compile your Android applications without the ADT plug-in Lets take a look at some of the more important tools in more detail.

The Android Emulator


The emulator is the perfect tool for testing and debugging your applications, particularly if you dont have a real device (or dont want to risk it) for experimentation. The emulator is an implementation of the Dalvik virtual machine, making it as valid a platform for running Android applications as any Android phone. Because its decoupled from any particular hardware, its an excellent baseline to use for testing your applications. A number of alternative user interfaces are available to represent different hardware configurations, each with different screen sizes, resolutions, orientations, and hardware features to simulate a variety of mobile device types. Full network connectivity is provided along with the ability to tweak the Internet connection speed and latency while debugging your applications. You can also simulate placing and receiving voice calls and SMS messages. The ADT plug-in integrates the emulator into Eclipse so that its launched automatically when you run or debug your projects. If you arent using the plug-in or want to use the emulator outside of Eclipse, you can telnet into the emulator and control it from its console. At this stage, the emulator doesnt implement all the mobile hardware features supported by Android, including the camera, vibration, LEDs, actual phone calls, the accelerometer, USB connections, Bluetooth, audio capture, battery charge level, and SD card insertion/ejection. Dalvik Debug Monitor Service (DDMS) The emulator lets you see how your application will look, behave, and interact, but to really see whats happening under the surface, you need the DDMS. The Dalvik Debug Monitoring Service is a powerful debugging tool that lets you interrogate active processes, view the stack and heap, watch and pause active threads, and explore the file system of any active emulator. The DDMS perspective in Eclipse also provides simplified access to screen captures of the emulator and the logs generated by LogCat. If youre using the ADT plug-in, the DDMS is fully integrated into Eclipse and is available from the DDMS perspective. If you arent using the plug-in or Eclipse, you can run DDMS from the command line, and it will automatically connect to any emulator thats running. The Android Debug Bridge (ADB) The Android debug bridge (ADB) is a client-service application that lets you connect with an Android Emulator or device. Its made up of three components: a daemon running on the emulator, a service that runs on your development hardware, and client applications (like the DDMS) that communicate with the daemon through the service. As a communications conduit between your development hardware and the Android device/emulator, the ADB lets you install applications, push and pull files, and run shell commands on the target device. Using the device shell, you can change logging settings, and query or modify SQLite databases available on the device. The ADT tool automates and simplifies a lot of the usual interaction with the ADB, including application installation and update, log files, and file transfer (through the DDMS perspective).

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Creating Your First Program


ADT comes with a built-in example program, or template, that were going to use to create a simple Hello, Android program in just a few seconds. Get your stopwatch ready. Ready? Set? Go! Select File > New > Project... to open the New Project dialog box. Then select Android > Android Project, and click Next. Enter the following information: Project name: HelloAndroid Build Target: Android 1.5 Application name: Hello, Android Package name: org.example.hello Create Activity: Hello When youre done, it should look something like Fig 1.2.Click Finish. The Android plug-in will create the project and fill it in with some default files. Eclipse will build it and package it up so it will be ready to execute. If you get an error about missing source folders, select Project > Clean to fix it. OK, that takes care of writing the program; now all thats left is to try running it. First well run it under the Android Emulator. Running on the Emulator To run your Android program, go to the Package Explorer window, right-click the HelloAndroid project, and select Run As > Android Application. If youre following along in Eclipse you may see an error dialog like the one in Fig 1.3. This indicates we havent told the Emulator what kind of phone to emulate. Creating an AVD, you need to create an Android Virtual Device (AVD), use Eclipse .Its easier to use Eclipse, so select Yes in the AVD Error dialog to open the AVD Manager. You can open the manager again later by selecting Window > Android AVD Manager. In the AVD Manager dialog, fill out the fields for the new AVD as follows:
Name: em15 Target: Android 1.5 - 1.5 SDCard: 128M Skin: Default (HVGA)

This tells Eclipse to set up a generic device called em15 which has the Android 1.5 (Cupcake) firmware installed. A 128MB virtual Secure Digital (SD) Card will be allocated, along with a half-VGA (320x480) display. When youre done you should see something like Figure 1.4, on the following page. Due to updates in the plug-in since this was written your screen may look slightly different. Click on Create AVD (not Finish) to create the virtual device. A few seconds later you should see a message that the device has been created. Click OK, and then you can click Finish.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Fig1.2 New Android project

Fig 1.3: Missing Android Virtual Device (AVD)


Name: em15 Target: Android 1.5 - 1.5 SDCard: 128M Skin: Default (HVGA)

This tells Eclipse to set up a generic device called em15 which has the Android 1.5 (Cupcake) firmware installed. A 128MB virtual Secure Digital (SD) Card will be allocated, along with a half-VGA (320x480) display. When youre done you should see something like Figure 1.4, on the following page. Due to updates in the plug-in since this was written your screen may look slightly different. Click on Create AVD (not Finish) to create the virtual device. A few seconds later you should see a message that the device has been created.Click OK, and then you can click Finish.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Fig 1.4: Creating an AVD in Eclipse

Once you have a valid AVD, the Android emulator window will start up and boot the Android operating system. The first time you do this, it may take a minute or two, so be patient. If you see an error message saying that the application is not responding, select the option to continue waiting. After the emulator window starts, Eclipse will send it a copy of your program to execute. The application screen comes up, and your Hello, Android program is now running (see Figure 1.5, on the next page). Thats it! Congratulations on your first Android program.

Fig 1.5: Running the Hello, Android program

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Android Architecture

Androids architecture encourages the concept of component reuse, allowing you to publish and share activities, services, and data with other applications with access managed by the security restrictions you put in place. The same mechanism that lets you produce a replacement contact manager or phone dialer can let you expose your application components to let other developers create new UI front ends and functionality extensions, or otherwise build on them. The following application services are the architectural cornerstones of all Android applications, providing the framework youll be using for your own software: Activity Manager : Controls the life cycle of your activities, including management of the activity stack Views : Are used to construct the user interfaces for your activities Notification Manager : Events such as arriving messages, appointments, proximity alerts, alien invasions, and more can be presented in an unobtrusive fashion to the user.. Content Providers : These objects encapsulate data that needs to be shared between applications, such as contacts. Resource Manager : Supports non-code resources like strings and graphics. Resources are anything that goes with your program that is not code. Location Manager : An Android phone always knows where it is.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Android Libraries
Android offers a number of APIs for developing your applications. The following list of core APIs should provide an insight into whats available; all Android devices will offer support for at least these APIs: android.util The core utility package contains low-level classes like specialized containers, string formatters, and XML parsing utilities. android.os The operating system package provides access to basic operating system services like message passing, interprocess communication, clock functions, and debugging. android.graphics The graphics API supplies the low-level graphics classes that support canvases, colors, and drawing primitives, and lets you draw on canvases. android.text The text processing tools for displaying and parsing text. android.database Supplies the low-level classes required for handling cursors when working with databases. android.content The content API is used to manage data access and publishing by providing services for dealing with resources, content providers, and packages. android.view Views are the core user interface class. All user interface elements are constructed using a series of Views to provide the user interaction components. android.widget Built on the View package, the widget classes are the heres one we created earlier user-interface elements for you to use in your applications. They include lists, buttons, and layouts. com.google.android.maps A high-level API that provides access to native map controls that you can use within your application. Includes the Map View control as well as the Overlay and MapController classes used to annotate and control your embedded maps. android.app A high-level package that provides access to the application model. The application package includes the Activity and Service APIs that form the basis for all your Android applications. android.provider To ease developer access to certain standard Content Providers (such as the contacts database), the Provider package offers classes to provide access to standard databases included in all Android distributions. android.telephony The telephony APIs give you the ability to directly interact with the devices phone stack, letting you make, receive, and monitor phone calls, phone status, and SMS messages. android.webkit The Webkit package features APIs for working with Web-based content, including a Web View control for embedding browsers in your activities and a cookie manager. In addition to the Android APIs, the Android stack includes a set of C/C++ libraries that are exposed through the application framework. These libraries include: OpenGL The library used to support 3D graphics based on the Open GL ES 1.0 API FreeType Support for bitmap and vector font rendering SGL The core library used to provide a 2D graphics engine libc The standard C library optimized for Linux-based embedded devices SQLite The lightweight relation database engine used to store application data SSL Support for using the Secure Sockets Layer cryptographic protocol for secure Internet Communications

What Makes an Android Application?


A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Android applications consist of loosely coupled components, bound using a project manifest that describes each component and how they interact. There are six components that provide the building blocks for your applications: Activities Your applications presentation layer. Every screen in your application will be an extension of the Activity class. Activities use Views to form graphical user interfaces that display information and respond to user actions. In terms of desktop development, an Activity is equivalent to a Form. Services The invisible workers of your application. Service components run invisibly, updating your data sources and visible Activities and triggering Notifications. Theyre used to perform regular processing that needs to continue even when your applications Activities arent active or visible. Content Providers A shareable data store. Content Providers are used to manage and share application databases. Content Providers are the preferred way of sharing data across application boundaries. This means that you can configure your own Content Providers to permit access from other applications and use Content Providers exposed by others to access their stored data. Android devices include several native Content Providers that expose useful databases like contact information. Intents A simple message-passing framework. Using Intents, you can broadcast messages system- wide or to a target Activity or Service, stating your intention to have an action performed. The system will then determine the target(s) that will perform any actions as appropriate. Broadcast Receivers Intent broadcast consumers. By creating and registering 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 ideal for event-driven applications. Notifications A user notification framework. Notifications let you signal users without stealing focus or interrupting their current Activities. Theyre the preferred technique for getting a users attention from within a Service or Broadcast Receiver. For example, when a device receives a text message or an incoming call, it alerts you by flashing lights, making sounds, displaying icons, or showing dialog messages. You can trigger these same events from your own applications using Notifications By decoupling the dependencies between application components, you can share and interchange individual pieces, such as Content Providers or Services, with other applications both your own and those of third parties.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Figure 1-1. Android Activity lifecycle

Android Activity Lifecycle


Android is designed around the unique requirements of mobile applications. In particular, Android recognizes that resources (memory and battery, for example) are limited on most mobile devices, and provides mechanisms to conserve those resources. The mechanisms are evident in the Android Activity Lifecycle, which defines the states or events that an activity goes through from the time it is created until it finishes running. The lifecycle is shown diagrammatically in Figure 1-1. 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 data files 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 onStop method. 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).
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

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 againand 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 youd 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. This is the first place in this book weve discussed how programming for mobile devices is different from programming for desktop devices, and there will be many more such places as you go through later chapters. Your users will appreciate it if you write your activities with the activity lifecycle in mind, and you will ultimately benefit.

Android Service Lifecycle


The lifecycle for a service is similar to that for an activity, but different in a few important details: onCreate and onStart differences Services can be started when a client calls the Context.startService(Intent) method. If the service isnt already running, Android starts it and calls its onCreate method followed by the onStart method. If the service is already running, its onStart method is invoked again with the new intent. So its quite possible and normal for a services onStart method to be called repeatedly in a single run of the service. onResume, onPause, and onStop are not needed Recall that a service generally has no user interface, so there isnt any need for the onPause, onResume, or onStop methods. Whenever a service is running, it is always in the background. onBind If a client needs a persistent connection to a service, it can call the Context.bind Service method. This creates the service if it is not running, and calls onCreate but not onStart. Instead, the onBind method is called with the clients intent, and it returns an IBind object that the client can use to make further calls to the service. Its quite normal for a service to have clients starting it and clients bound to it at the same time. onDestroy As with an activity, the onDestroy method is called when the service is about to be terminated. Android will terminate a service when there are no more clients starting or bound to it. As with activities, Android may also
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

terminate a service when memory is getting low. If that happens, Android will attempt to restart the service when the memory pressure passes, so if your service needs to store persistent information for that restart, its best to do so in the onStart method.

Chapter-3

Project Structure
The Android build system is organized around a specific directory tree structure for your Android project, much like any other Java project. The specifics, though, are fairly unique to Android and what it does to prepare the actual application that will run on the device or emulator.

Root Contents
When you create a new Android project (e.g., via the activity creator script or an Android-enabled IDE), you get several items in the projects root directory: AndroidManifest.xml, an XML file describing the application being built and what componentsactivities, services, etc.are being supplied by that application build.xml, an Ant1 script for compiling the application and installing it on the device default. properties, a property file used by the Ant build script bin/ holds the application once it is compiled libs/ holds any third-party Java JARs your application requires src/ holds the Java source code for the application res/ holds resources, such as icons, GUI layouts, and the like, that get packaged with the compiled Java in the application assets/ holds other static files you wish packaged with the application for deployment onto the device

The Sweat of Your Brow


When you create an Android project (e.g., via activity creator), you supply the fully-qualified Classname of the main activity for the application (eg.,com.commonsware.android.Some Demo) .You will then find that your projects src/ tree already has the namespace directory tree in place, plus a stub Activity subclass representing your main activity (e.g., src/com/commonsware/android/SomeDemo.java). You are welcome to modify this file and add others to the src/ tree as needed to implement your application. The first time you compile the project (e.g., via ant), out in the main activitys name space directory, the Android build chain will create R.java. This contains a number of constants tied to the various resources you placed out in the res/ directory tree. You should not modify R.java yourself, letting the Android tools handle it for you.

The Rest of the Story

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

As already mentioned, the res/ directory tree holds resourcesstatic files that are packaged along with your application, either in their original form or, occasionally, in a preprocessed form. Some of the subdirectories you will find or create under res/ include res/drawable/ for images (PNG, JPEG, etc.) res/layout/ for XML-based UI layout specifications res/menu/ for XML-based menu specifications res/raw/ for general-purpose files (e.g., a CSV file of account information) res/values/ for strings, dimensions, and the like res/xml/ for other general-purpose XML files you wish to ship

What You Get Out of It


When you compile your project (via ant or the IDE), the results go into the bin/ directory under your project root, specifically: bin/classes/ holds the compiled Java classes bin/classes.dex holds the executable created from those compiled Java classes bin/yourapp.ap holds your applications resources, packaged as a ZIP file (where yourapp is the name of your application) bin/yourapp-debug.apk or bin/yourapp-unsigned.apk is the actual Android application (where yourapp is the name of your application) The .apk file is a ZIP archive containing the .dex file, the compiled edition of your resources (resources. arsc), any un-compiled resources (such as what you put in res/raw/) and the AndroidManifest.xml file. It is also digitally signed, with the -debug portion of the filename indicating it has been signed using a debug key that works with the emulator, or unsigned indicating that you built your application for release (ant release), but the APK still needs to be signed using jar signer and an official key.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Chapter-4 Creating User Interfaces


1. Layouts
A layout is a class that handles arranging the way its children appear on the screen. Anything that is a View can be a child of a layout. All of the layouts inherit from ViewGroup. The standard layouts are: Tab layout Table layout Linear layout Frame layout Relative layout Absolute layout

Absolute layout:
Absolute layout is based on the simple idea of placing each control at an absolute position. You specify the exact x and y co-ordinates on the screen for each control. XML layout using AbsoluteLayout -: <AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/backbutton" android:text="Back" android:layout_x="10px" android:layout_y="5px" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_x="10px" android:layout_y="110px" android:text="First Name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:layout_x="150px" android:layout_y="100px" android:width="100px" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

android:layout_x="10px" android:layout_y="160px" android:text="Last Name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:layout_x="150px" android:layout_y="150px" android:width="100px" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </AbsoluteLayout>

Frame Layout
FrameLayout is designed to display a single item at a time. You can have multiple elements within a FrameLayout but each element will be positioned based on the top left of the screen. Elements that overlap will be displayed overlapping. XML layout using FrameLayout<FrameLayout android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <ImageView android:src="@drawable/icon" android:scaleType="fitCenter" android:layout_height="fill_parent" android:layout_width="fill_parent"/> <TextView android:text="Learn-Android.com" android:textSize="24sp" android:textColor="#000000" android:layout_height="fill_parent" android:layout_width="fill_parent" android:gravity="center"/> </FrameLayout>

Linear Layout:
LinearLayout organizes elements along a single line. You specify whether that line is verticle or horizontal using android: orientation. XML layout using LinearLayout -: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/backbutton" android:text="Back" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:text="First Name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:width="100px" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:text="Last Name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:width="100px" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>

Relative Layout:
RelativeLayout lays out elements based on their relationships with one another, and with the parent container. This is arguably the most complicated layout, and we need several properties to actually get the layout we want.

Relative To Container:
These properties will layout elements relative to the parent container.

android:layout_alignParentBottom Places the bottom of the element on the bottom of the container android:layout_alignParentLeft Places the left of the element on the left side of the container android:layout_alignParentRight Places the right of the element on the right side of the container android:layout_alignParentTop Places the element at the top of the container android:layout_centerHorizontal Centers the element horizontally within its parent container android:layout_centerInParent Centers the element both horizontally and vertically within its container android:layout_centerVertical Centers the element vertically within its parent container

Relative To Other Elements:


These properties allow you to layout elements relative to other elements on screen. The value for each of these elements is the id of the element you are using to layout the new element. Each element that is used in this way must have an ID defined using android:id=@+id/XXXXX where XXXXX is replaced with the desired id.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

You use @id/XXXXX to reference an element by its id. One thing to remember is that referencing an element before it has been declared will produce an error.

android:layout_above Places the element above the specified element android:layout_below Places the element below the specified element android:layout_toLeftOf Places the element to the left of the specified element android:layout_toRightOf Places the element to the right of the specified element

Alignment With Other Elements:


These properties allow you to specify how elements are aligned in relation to other elements.

android:layout_alignBaseline Aligns baseline of the new element with the baseline of the specified element android:layout_alignBottom Aligns the bottom of new element in with the bottom of the specified element android:layout_alignLeft Aligns left edge of the new element with the left edge of the specified element android:layout_alignRight Aligns right edge of the new element with the right edge of the specified element android:layout_alignTop Places top of the new element in alignment with the top of the specified element

XML layout using Relative Layout<RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <Button android:id="@+id/backbutton" android:text="Back" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/firstName" android:text="First Name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/backbutton" /> <EditText android:width="100px" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/firstName" android:layout_alignBaseline="@id/firstName" /> <TextView android:id="@+id/lastName" android:text="Last Name" android:layout_width="wrap_content"
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

android:layout_height="wrap_content" android:layout_below="@id/firstName" /> <EditText android:width="100px" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/lastName" android:layout_alignBaseline="@id/lastName" /> </RelativeLayout>

Table Layout
TableLayout organizes content into rows and columns. The rows are defined in the layout XML, and the columns are determined automatically by Android. This is done by creating at least one column for each element. So, for example, if you had a row with two elements and a row with five elements then you would have a layout with two rows and five columns. You can specify that an element should occupy more than one column using android:layout_span. This can increase the total column count as well, so if we have a row with two elements and each element has android:layout_span=3 then you will have at least six columns in your table. By default, Android places each element in the first unused column in the row. You can, however, specify the column an element should occupy using android:layout_column. XML layout using Relative Layout<TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <TableRow> <Button android:id="@+id/backbutton" android:text="Back" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </TableRow> <TableRow> <TextView android:text="First Name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" /> <EditText android:width="100px" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </TableRow>
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

<TableRow> <TextView android:text="Last Name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" /> <EditText android:width="100px" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </TableRow> </TableLayout> 2. Buttons <Button android:id="@+id/button01" android:text="BUTTON 1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:typeface="serif" android:textStyle="bold" /> <Button android:id="@+id/button02" android:text="BUTTON 2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:typeface="serif" android:textStyle="bold" /> <Button android:id="@+id/button03" android:text="BUTTON 3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:typeface="serif" android:textStyle="bold" /> TextView: <TextView android:id="@+id/plain" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Plain" /> <TextView android:id="@+id/serif" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Serif"
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

android:typeface="serif" /> <TextView android:id="@+id/bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Bold" android:textStyle="bold" /> <TextView android:id="@+id/italic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Italic" android:textStyle="italic" />

EditText: <EditText android:id="@+id/editText1" android:text="EditText 01" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/button2" android:text="(206)555-1212" android:typeface="serif" android:phoneNumber="true" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/password" android:text="SuperSecret" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:password="true" />

Spinner: <Spinner android:id="@+id/widget1" android:layout_width="fill_parent" android:layout_height="wrap_content"


A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

android:drawSelectorOnTop="false"/>

CheckBox: <CheckBox android:id="@+id/plain_cb" android:text="Plain" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <CheckBox android:id="@+id/serif_cb" android:text="Serif" android:layout_width="wrap_content" android:layout_height="wrap_content" android:typeface="serif" /> <CheckBox android:id="@+id/bold_cb" android:text="Bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" /> <CheckBox android:id ="@+id/italic_cb" android:text="Italic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="italic" />

Android Menus:
Android Menus can be classified into 3 types:

Options Menu Context Menu Submenu

Options Menu:
Options Menu is the menu displayed when MENU key on the device is clicked.Options menu is divided into 2 types: Icon Menu and Expanded Menu, based on the number of menu options. Options menu can have any
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

number of menu options, but only the first six options are shown directly when the MENU key is clicked and this is called as Icon Menu. In case there are more than six options then first five are show directly and remaining are available when More button is clicked and is called as Expanded Menu. Important Points:

onCreateOptionsMenu() method of the Activity is called when the user clicks the Menu Key of the device. So override this method in the activity and populate the Menu object passed as parameter to this method.

Multiple add() methods are available. Use the one that accepts itemId as a parameter. onOptionItemSelected() method of the activity is called when a particular Item/Option of the menu is clicked. Override this method in the activity and implement your code to perform the corresponding actions based on the menu option selected.

setIcon() is used for assigning icon with the option.

The listing below shows how to add a menu dynamically via code public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_ADD, 0, "Add").setIcon(R.drawable.ic_menu_add); menu.add(0, MENU_DELETE, 0, "Delete").setIcon(R.drawable.ic_menu_delete); menu.add(0, MENU_SAVE, 0, "Save").setIcon(R.drawable.ic_menu_save); menu.add(0, MENU_DONE, 0, "Done").setIcon(R.drawable.ic_menu_done); menu.add(0, MENU_HELP, 0, "Help").setIcon(R.drawable.ic_menu_help); menu.add(0, MENU_SETTINGS, 0, Settings").setIcon(R.drawable.ic_menu_settings); menu.add(0, MENU_EXIT, 0, "Exit").setIcon(R.drawable.ic_menu_exit); return true; } The listing below shows how to you can react to different menu items that are clicked. We are only displaying the template below. The actual implementation when a specific menu item is clicked depends on your application. @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0,0,0,"add");
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

menu.add(0,1,0,"remove"); menu.add(0,2,0,"edit"); menu.add(0,3,0,"cut"); menu.add(0,4,0,"paste"); return true; }

public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); TextView view = (TextView) findViewById(R.id.Text_View); switch (item.getItemId()) { case 0: view.setText("This is"+item.getTitle()); break; case 1: view.setText("This is"+item.getTitle()); break; default: view.setText("Debug."); break; } return false; }

@Override public boolean onPrepareOptionsMenu(Menu menu) { return super.onPrepareOptionsMenu(menu); }

Context Menu:
Android provides the facility to open a menu in context with the object clicked. A Long-press on the view will bring up the registered Context menu. Important Points
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Using registerForContextMenu() method view is registered for context menu. onCreateContextMenu() method of Activity is called on click (long-press) of registered view. So override this method to populate Context menu options.

onContextItemSelected() method of activity is called whenever item/option from context menu is selected. Override this method to perform the appropriate operations depending on the option selected. public void onCreateContextMenu(ContextMenu menu, View v,

ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);

menu.add(0, MENU_ADD, 0, "Edit");

menu.add(0, MENU_DELETE, 0, "Delete");

public boolean onContextItemSelected(MenuItem item) {

switch(item.getItemId()){

case MENU_ADD:

// Add

return true;

case MENU_DELETE:

// Delete

return true;

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

default:

return false;

} Menu Using XML Menu can also be defined and populated using XML. Following XML structure represents the same menu as of above. Create optionsmenu.xml under folder res/menu <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/MENU_ADD" android:title="Add" android:icon="@drawable/ic_menu_add"/> <item android:title="Delete" android:id="@+id/MENU_DELETE" android:icon="@drawable/ic_menu_delete"/> <item android:title="Save" android:id="@+id/MENU_SAVE" android:icon="@drawable/ic_menu_save"/> <item android:title="Done" android:id="@+id/MENU_DONE" android:icon="@drawable/ic_menu_done"/> <item android:title="Help" android:id="@+id/MENU_HELP"
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

android:icon="@drawable/ic_menu_help"/> <item android:title="Settings" android:id="@+id/MENU_SETTINGS" android:icon="@drawable/ic_menu_settings"/> <item android:title="Exit" android:id="@+id/MENU_EXIT" android:icon="@drawable/ic_menu_exit"/> </menu>

public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = new MenuInflater(this); inflater.inflate(R.menu.optionsmenu, menu); return true; } Advantages of using XML for creating menu are:

Easily maintain/modify the menu structure due to a clear separation of the menu creation from the code. The code in onCreateOptionsMenu() method is reduced.

Submenus
Sub menu can be added to any type of menu. Below code shows adding Submenu for Options menu:

public boolean onCreateOptionsMenu(Menu menu) {

SubMenu sendMenu = menu.addSubMenu("Send");

sendMenu.add(0,MENU_SMS,0,"SMS");

sendMenu.add(0,MENU_EMAIL,0,"EMAIL");

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

return true;

public boolean onOptionsItemSelected(MenuItem item) {

switch(item.getItemId()){

case MENU_SMS:

// SMS

return true;

case MENU_EMAIL:

// Email

return true;

default:

return false;

} In XML <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/MENU_SEND" android:title="Send">


A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

<menu> <item android:id="@+id/MENU_SMS" android:title="SMS"></item> <item android:id="@+id/MENU_EMAIL" android:title="EMAIL"></item> </menu> </item> </menu>

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Вам также может понравиться