Quick Start
Quick Start
Quick Start
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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
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.
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.
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
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
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
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
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" />
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:
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.
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
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; }
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);
switch(item.getItemId()){
case MENU_ADD:
// Add
return true;
case MENU_DELETE:
// Delete
return true;
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:
sendMenu.add(0,MENU_SMS,0,"SMS");
sendMenu.add(0,MENU_EMAIL,0,"EMAIL");
return true;
switch(item.getItemId()){
case MENU_SMS:
// SMS
return true;
case MENU_EMAIL:
return true;
default:
return false;
<menu> <item android:id="@+id/MENU_SMS" android:title="SMS"></item> <item android:id="@+id/MENU_EMAIL" android:title="EMAIL"></item> </menu> </item> </menu>