Table of Content Android Tutorial... 2 Audience... 2 Prerequisites... 2 Copyright & Disclaimer Notice... 2 Overview... 7

Size: px
Start display at page:

Download "Table of Content Android Tutorial... 2 Audience... 2 Prerequisites... 2 Copyright & Disclaimer Notice... 2 Overview... 7"

Transcription

1 Android Tutorial

2 Table of Content Android Tutorial... 2 Audience... 2 Prerequisites... 2 Copyright & Disclaimer Notice... 2 Overview... 7 Features of Android... 7 Android Applications... 8 Environment Setup... 9 Step 1 - Setup Java Development Kit (JDK)... 9 Step 2 - Setup Android SDK Step 3 - Setup Eclipse IDE Step 4 - Setup Android Development Tools (ADT) Plugin Step 5 - Create Android Virtual Device Architecture Linux kernel Libraries Android Runtime Application Framework Applications Application Components Activities Services Broadcast Receivers Content Providers Additional Components Hello World Example Create Android Application Anatomy of Android Application The Main Activity File The Manifest File The Strings File The R File The Layout File Running the Application Resources Organizing & Accessing Alternative Resources... 30

3 Accessing Resources ACCESSING RESOURCES IN CODE EXAMPLE: EXAMPLE: EXAMPLE: ACCESSING RESOURCES IN XML Activities Example Services Example Broadcast Recievers Creating the Broadcast Receiver Registering Broadcast Receiver Broadcasting Custom Intents Example Content Providers Content URIs Create Content Provider Example Fragments Fragment Life Cycle How to use Fragments? Example Intents and Filters Intent Objects ACTION Android Intent Standard Actions: DATA CATEGORY EXTRAS FLAGS COMPONENT NAME Types of Intents EXPLICIT INTENTS IMPLICIT INTENTS Example Intent Filters Example UI Layouts... 92

4 Android Layout Types Example RelativeLayout Attributes Example GridView Attributes Example Sub-Activity Example Layout Attributes View Identification UI Controls Android UI Controls TextView TextView Attributes Example Exercise: EditText EditText Attributes Example Exercise: AutoCompleteTextView AutoCompleteTextView Attributes Example Exercise: Button Button Attributes Example Exercise: ImageButton ImageButton Attributes Example Exercise: CheckBox CheckBox Attributes Example Exercise: ToggleButton ToggleButton Attributes Example Exercise:

5 RadioButton RadioButton Attributes Example Exercise: RadioGroup RadioGroup Attributes Example Exercise: Create UI Controls Event Handling Event Listeners & Event Handlers Event Listeners Registration: Event Handling Examples EVENT LISTENERS REGISTRATION USING AN ANONYMOUS INNER CLASS 173 REGISTRATION USING THE ACTIVITY IMPLEMENTS LISTENER INTERFACE 176 REGISTRATION USING LAYOUT FILE ACTIVITY_MAIN.XML Exercise: Styles and Themes Defining Styles Using Styles Style Inheritance Android Themes Default Styles & Themes Custom Components Creating a Simple Custom Component INSTANTIATE USING CODE INSIDE ACTIVITY CLASS INSTANTIATE USING LAYOUT XML FILE Custom Component with Custom Attributes STEP STEP STEP Example Big View Notification

6 CHAPTER 1 Overview What is Android? Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android. The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 where as the first commercial version, Android 1.0, was released in September On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of functionality and performance. The source code for Android is available under free and open source software licenses. Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel changes, under the GNU General Public License version 2. Features of Android Android is a powerful operating system competing with Apple 4GS and supports great features. Few of them are listed below: Feature Beautiful UI Connectivity Storage Media support Messaging Description Android OS basic screen provides a beautiful and intuitive user interface. GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and WiMAX. SQLite, a lightweight relational database, is used for data storage purposes. H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP SMS and MMS

7 Web browser Multi-touch Multi-tasking Resizable widgets Multi-Language GCM Wi-Fi Direct Based on the open-source WebKit layout engine, coupled with Chrome's V8 JavaScript engine supporting HTML5 and CSS3. Android has native support for multi-touch which was initially made available in handsets such as the HTC Hero. User can jump from one task to another and same time various application can run simultaneously. Widgets are resizable, so users can expand them to show more content or shrink them to save space Supports single direction and bi-directional text. Google Cloud Messaging (GCM) is a service that lets developers send short message data to their users on Android devices, without needing a proprietary sync solution. A technology that lets apps discover and pair directly, over a high-bandwidth peer-to-peer connection. Android Beam Android Applications A popular NFC-based technology that lets users instantly share, just by touching two NFCenabled phones together. Android applications are usually developed in the Java language using the Android Software Development Kit. Once developed, Android applications can be packaged easily and sold out either through a store such as Google Play or the Amazon Appstore. Android powers hundreds of millions of mobile devices in more than 190 countries around the world. It's the largest installed base of any mobile platform and growing fast. Every day more than 1 million new Android devices are activated worldwide. This tutorial has been written with an aim to teach you how to develop and package Android application. We will start from environment setup for Android application programming and then drill down to look into various aspects of Android applications.

8 CHAPTER 2 Environment Setup You will be glad to know that you can start your Android application development on either of the following operating systems: Microsoft Windows XP or later version. Mac OS X or later version with Intel chip. Linux including GNU C Library 2.7 or later. Second point is that all the required tools to develop Android applications are freely available and can be downloaded from the Web. Following is the list of software's you will need before you start your Android application programming. Java JDK5 or JDK6 Android SDK Eclipse IDE for Java Developers (optional) Android Development Tools (ADT) Eclipse Plugin (optional) Here last two components are optional and if you are working on Windows machine then these components make your life easy while doing Java based application development. So let us have a look how to proceed to set required environment. Step 1 - Setup Java Development Kit (JDK) You can download the latest version of Java JDK from Oracle's Java site: Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the JDK in C:\jdk1.6.0_15, you would have to put the following line in your C:\autoexec.bat file. set PATH=C:\jdk1.6.0_15\bin;%PATH% set JAVA_HOME=C:\jdk1.6.0_15

9 Alternatively, you could also right-click on My Computer, select Properties, then Advanced, thenenvironment Variables. Then, you would update the PATH value and press the OK button. On Linux, if the SDK is installed in /usr/local/jdk1.6.0_15 and you use the C shell, you would put the following code into your.cshrc file. setenv PATH /usr/local/jdk1.6.0_15/bin:$path setenv JAVA_HOME /usr/local/jdk1.6.0_15 Alternatively, if you use an Integrated Development Environment (IDE) Eclipse, then it will know automatically where you have installed your Java. Step 2 - Setup Android SDK You can download the latest version of Android SDK from Android official website : Android SDK Downloads. If you are installing SDK on Windows machine, then you will find a installer_rxx-windows.exe, so just download and run this exe which will launch Android SDK Tool Setup wizard to guide you throughout of the installation, so just follow the instructions carefully. Finally you will haveandroid SDK Tools installed on your machine. If you are installing SDK either on Mac OS or Linux, check the instructions provided along with the downloaded android-sdk_rxx-macosx.zip file for Mac OS and android-sdk_rxx-linux.tgz file for Linux. This tutorial will consider that you are going to setup your environment on Windows machine having Windows 7 operating system. So let's launch Android SDK Manager using the option All Programs > Android SDK Tools > SDK Manager, this will give you following window: Once you launched SDK manager, its time to install other required packages. By default it will list down total 7 packages to be installed, but I will suggest to de-select Documentation for Android SDK andsamples for

10 SDK packages to reduce installation time. Next click Install 7 Packages button to proceed, which will display following dialogue box: If you agree to install all the packages, select Accept All radio button and proceed by clicking Installbutton. Now let SDK manager do its work and you go, pick up a cup of coffee and wait until all the packages are installed. It may take some time depending on your internet connection. Once all the packages are installed, you can close SDK manager using top-right cross button. Step 3 - Setup Eclipse IDE All the examples in this tutorial have been written using Eclipse IDE. So I would suggest you should have latest version of Eclipse installed on your machine. To install Eclipse IDE, download the latest Eclipse binaries from Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\eclipse on windows, or /usr/local/eclipse on Linux and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exe %C:\eclipse\eclipse.exe Eclipse can be started by executing the following commands on Linux machine: $/usr/local/eclipse/eclipse After a successful startup, if everything is fine then it should display following result:

11 Step 4 - Setup Android Development Tools (ADT) Plugin This step will help you in setting Android Development Tool plugin for Eclipse. Let's start with launching Eclipse and then, choose Help > Software Updates > Install New Software. This will display the following dialogue box.

12 Now use Add button to add ADT Plugin as name and as the location. Then click OK to add this location, as soon as you will click OK button to add this location, Eclipse starts searching for the plug-in available the given location and finally lists down the found plugins.

13 Now select all the listed plug-ins using Select All button and click Next button which will guide you ahead to install Android Development Tools and other required plugins. Step 5 - Create Android Virtual Device To test your Android applications you will need a virtual Android device. So before we start writing our code, let us create an Android virtual device. Launch Android AVD Manager using Eclipse menu optionswindow > AVD Manager> which will launch Android AVD Manager. Use New button to create a new Android Virtual Device and enter the following information, before clicking Create AVD button.

14 If your AVD is created successfully it means your environment is ready for Android application development. If you like, you can close this window using top-right cross button. Better you re-start your machine and once you are done with this last step, you are ready to proceed for your first Android example but before that we will see few more important concepts related to Android Application Development.

15 CHAPTER 3 Architecture Android operating system is a stack of software components which is roughly divided into five sections and four main layers as shown below in the architecture diagram. Linux kernel At the bottom of the layers is Linux - Linux 2.6 with approximately 115 patches. This provides basic system functionality like process management, memory management, device management like camera, keypad, display etc. Also, the kernel handles all the things that Linux is really good at such as networking and a vast array of device drivers, which take the pain out of interfacing to peripheral hardware.

16 Libraries On top of Linux kernel there is a set of libraries including open-source Web browser engine WebKit, well known library libc, SQLite database which is a useful repository for storage and sharing of application data, libraries to play and record audio and video, SSL libraries responsible for Internet security etc. Android Runtime This is the third section of the architecture and available on the second layer from the bottom. This section provides a key component called Dalvik Virtual Machine which is a kind of Java Virtual Machine specially designed and optimized for Android. The Dalvik VM makes use of Linux core features like memory management and multi-threading, which is intrinsic in the Java language. The Dalvik VM enables every Android application to run in its own process, with its own instance of the Dalvik virtual machine. The Android runtime also provides a set of core libraries which enable Android application developers to write Android applications using standard Java programming language. Application Framework The Application Framework layer provides many higher-level services to applications in the form of Java classes. Application developers are allowed to make use of these services in their applications. Applications You will find all the Android application at the top layer. You will write your application to be installed on this layer only. Examples of such applications are Contacts Books, Browser, Games etc.

17 CHAPTER 4 Application Components Application components are the essential building blocks of an Android application. These components are loosely coupled by the application manifest file AndroidManifest.xml that describes each component of the application and how they interact. There are following four main components that can be used within an Android application: Components Activities Services Broadcast Receivers Content Providers Activities Description They they dictate the UI and handle the user interaction to the smartphone screen They handle background processing associated with an application. They handle communication between Android OS and applications. They handle data and database management issues. An activity represents a single screen with a user interface. For example, an application might have one activity that shows a list of new s, another activity to compose an , and another activity for reading s. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched. An activity is implemented as a subclass of Activity class as follows: public class MainActivity extends Activity { Services A service is a component that runs in the background to perform long-running operations. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity. A service is implemented as a subclass of Service class as follows: public class MyService extends Service {

18 Broadcast Receivers Broadcast Receivers simply respond to broadcast messages from other applications or from the system. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action. A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message is broadcasted as an Intent object. public class MyReceiver extends BroadcastReceiver { Content Providers A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. The data may be stored in the file system, the database or somewhere else entirely. A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions. public class MyContentProvider extends ContentProvider { We will go through these tags in detail while covering application components in individual chapters. Additional Components There are additional components which will be used in the construction of above mentioned entities, their logic, and wiring between them. These components are: Components Fragments Views Layouts Intents Resources Manifest Description Represents a behavior or a portion of user interface in an Activity. UI elements that are drawn onscreen including buttons, lists forms etc. View hierarchies that control screen format and appearance of the views. Messages wiring components together. External elements, such as strings, constants and drawables pictures. Configuration file for the application.

19 CHAPTER 5 Hello World Example Let us start actual programming with Android Framework. Before you start writing your first example using Android SDK, you have to make sure that you have setup your Android development environment properly as explained in Android - Environment Setup tutorial. I also assume that you have a little bit working knowledge with Eclipse IDE. So let us proceed to write a simple Android Application which will print "Hello World!". Create Android Application The first step is to create a simple Android Application using Eclipse IDE. Follow the option File -> New -> Project and finally select Android New Application wizard from the wizard list. Now name your application as HelloWorld using the wizard window as follows:

20 Next, follow the instructions provided and keep all other entries as default till the final step. Once your project is created successfully, you will have following project screen:

21 Anatomy of Android Application Before you run your app, you should be aware of a few directories and files in the Android project:

22 S.N. Folder, File & Description src This contains the.java source files for your project. By default, it includes an MainActivity.javasource file having an activity class that runs when your app is launched using the app icon. gen This contains the.r file, a compiler-generated file that references all the resources found in your project. You should not modify this file. bin This folder contains the Android package files.apk built by the ADT during the build process and everything

23 else needed to run an Android application res/drawable-hdpi This is a directory for drawable objects that are designed for high-density screens. res/layout This is a directory for files that define your app's user interface. res/values This is a directory for other various XML files that contain a collection of resources, such as strings and colors definitions. AndroidManifest.xml This is the manifest file which describes the fundamental characteristics of the app and defines each of its components. Following section will give a brief overview few of the important application files. The Main Activity File The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a Dalvik executable and runs your application. Following is the default code generated by the application wizard for Hello World! application: package com.example.helloworld; import android.os.bundle; import android.app.activity; import android.view.menu; import android.view.menuitem; import android.support.v4.app.navutils; public class MainActivity extends Activity public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.activity_main, menu); return true; Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder. TheonCreate() method is one of many methods that are fi red when an activity is loaded. The Manifest File Whatever component you develop as a part of your application, you must declare all its components in a manifest file called AndroidManifest.xml which ressides at the root of the application project directory. This file works as an interface between Android OS and your application, so if you do not declare your component in this file, then it will not be considered by the OS. For example, a default manifest file will look like as following file: <manifest xmlns:android=" package="com.example.helloworld" android:versioncode="1"

24 android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="15" /> <application > <activity android:name=".mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher"/> </intent-filter> </activity> </application> </manifest> Here <application>...</application> tags enclosed the components related to the application. Attributeandroid:icon will point to the application icon available under res/drawable-hdpi. The application uses the image named ic_launcher.png located in the drawable folders The <activity> tag is used to specify an activity and android:name attribute specifies the fully qualified class name of the Activity subclass and the android:label attributes specifies a string to use as the label for the activity. You can specify multiple activities using <activity> tags. The action for the intent filter is named android.intent.action.main to indicate that this activity serves as the entry point for the application. The category for the intent-filter is namedandroid.intent.category.launcher to indicate that the application can be launched from the device's launcher icon. refers to the strings.xml file explained below. refers to theapp_name string defined in the strings.xml fi le, which is "HelloWorld". Similar way, other strings get populated in the application. Following is the list of tags which you will use in your manifest file to specify different Android application components: <activity>elements for activities <service> elements for services <receiver> elements for broadcast receivers <provider> elements for content providers The Strings File The strings.xml file is located in the res/values folder and it contains all the text that your application uses. For example, the names of buttons, labels, default text, and similar types of strings go into this file. This file is responsible for their textual content. For example, a default strings file will look like as following file: <resources> <string name="app_name">helloworld</string> <string name="hello_world">hello world!</string> <string name="menu_settings">settings</string> <string name="title_activity_main">mainactivity</string> </resources>

25 The R File The gen/com.example.helloworld/r.java file is the glue between the activity Java files likemainactivity.java and the resources like strings.xml. It is an automatically generated file and you should not modify the content of the R.java file. Following is a sample of R.java file: /* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.example.helloworld; public final class R { public static final class attr { public static final class dimen { public static final int padding_large=0x7f040002; public static final int padding_medium=0x7f040001; public static final int padding_small=0x7f040000; public static final class drawable { public static final int ic_action_search=0x7f020000; public static final int ic_launcher=0x7f020001; public static final class id { public static final int menu_settings=0x7f080000; public static final class layout { public static final int activity_main=0x7f030000; public static final class menu { public static final int activity_main=0x7f070000; public static final class string { public static final int app_name=0x7f050000; public static final int hello_world=0x7f050001; public static final int menu_settings=0x7f050002; public static final int title_activity_main=0x7f050003; public static final class style { public static final int AppTheme=0x7f060000; The Layout File The activity_main.xml is a layout file available in res/layout directory, that is referenced by your application when building its interface. You will modify this file very frequently to change the layout of your application. For your "Hello World!" application, this file will have following content related to default layout: <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView

26 android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:layout_centervertical="true" tools:context=".mainactivity" /> </RelativeLayout> This is an example of simple RelativeLayout which we will study in a separate chapter. The TextView is an Android control used to build the GUI and it have various attribuites like android:layout_width,android:layout_height etc which are being used to set its width and height etc. refers to the strings.xml file located in the res/values folder. refers to the hello string defined in the strings.xml fi le, which is "Hello World!". Running the Application Let's try to run our Hello World! application we just created. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

27 Congratulations!!! you have developed your first Android Application and now just keep following rest of the tutorial step by step to become a great Android Developer. All the very best.

28 CHAPTER 6 Resources Organizing & Accessing There are many more items which you use to build a good Android application. Apart from coding for the application, you take care of various other resources like static content that your code uses, such as bitmaps, colors, layout definitions, user interface strings, animation instructions, and more. These resources are always maintained separately in various sub-directories under res/ directory of the project. This tutorial will explain you how you can organize your application resources, specify alternative resources and access them in your applications. Organize Resources You should place each type of resource in a specific subdirectory of your project's res/ directory. For example, here's the file hierarchy for a simple project: MyProject/ src/ MyActivity.java res/ drawable/ icon.png layout/ activity_main.xml info.xml values/ strings.xml The res/ directory contains all the resources in various subdirectories. Here we have an image resource, two layout resources, and a string resource file. Following table gives a detail about the resource directories supported inside project res/ directory. Directory anim/ color/ Resource Type XML files that define property animations. They are saved in res/anim/ folder and accessed from the R.anim class. XML files that define a state list of colors. They are saved in res/color/ and accessed

29 from the R.color class. drawable/ layout/ menu/ raw/ values/ Image files like.png,.jpg,.gif or XML files that are compiled into bitmaps, state lists, shapes, animation drawables. They are saved in res/drawable/ and accessed from the R.drawable class. XML files that define a user interface layout. They are saved in res/layout/ and accessed from the R.layout class. XML files that define application menus, such as an Options Menu, Context Menu, or Sub Menu. They are saved in res/menu/ and accessed from ther.menu class. Arbitrary files to save in their raw form. You need to callresources.openrawresource() with the resource ID, which is R.raw.filename to open such raw files. XML files that contain simple values, such as strings, integers, and colors. For example, here are some filename conventions for resources you can create in this directory: arrays.xml for resource arrays, and accessed from the R.array class. integers.xml for resource integers, and accessed from the R.integerclass. bools.xml for resource boolean, and accessed from the R.bool class. colors.xml for color values, and accessed from the R.color class. dimens.xml for dimension values, and accessed from the R.dimen class. strings.xml for string values, and accessed from the R.string class. styles.xml for styles, and accessed from the R.style class. xml/ Arbitrary XML files that can be read at runtime by calling Resources.getXML(). You can save various configuration files here which will be used at run time. Alternative Resources Your application should provide alternative resources to support specific device configurations. For example, you should include alternative drawable resources ( ie.images ) for different screen resolution and alternative string resources for different languages. At runtime, Android detects the current device configuration and loads the appropriate resources for your application. To specify configuration-specific alternatives for a set of resources, follow the following steps: Create a new directory in res/ named in the form <resources_name>-<config_qualifier>. Hereresources_name will be any of the resources mentioned in the above table, like layout, drawable etc. The qualifier will specify an individual configuration for which these resources are to be used. You can check official documentation for a complete list of qualifiers for different type of resources. Save the respective alternative resources in this new directory. The resource files must be named exactly the same as the default resource files as shown in the below example, but these files will have content specific to the alternative. For example though image file name will be same but for high resolution screen, its resolution will be high. Below is an example which specifies images for a default screen and alternative images for high resolution screen. MyProject/ src/ MyActivity.java res/ drawable/ icon.png background.png

30 drawable-hdpi/ icon.png background.png layout/ activity_main.xml info.xml values/ strings.xml Below is another example which specifies layout for a default language and alternative layout for arabic language. MyProject/ src/ MyActivity.java res/ drawable/ icon.png background.png drawable-hdpi/ icon.png background.png layout/ activity_main.xml info.xml layout-ar/ main.xml values/ strings.xml Accessing Resources During your application development you will need to access defined resources either in your code, or in your layout XML files. Following section explains how to access your resources in both the scenarios: ACCESSING RESOURCES IN CODE When your Android application is compiled, a R class gets generated, which contains resource IDs for all the resources available in your res/ directory. You can use R class to access that resource using sub-directory and resource name or directly resource ID. EXAMPLE: To access res/drawable/myimage.png and set an ImageView you will use following code: ImageView imageview = (ImageView) findviewbyid(r.id.myimageview); imageview.setimageresource(r.drawable.myimage); Here first line of the code make use of R.id.myimageview to get ImageView defined with idmyimageview in a Layout file. Second line of code makes use of R.drawable.myimage to get an image with name myimage available in drawable sub-directory under /res. EXAMPLE: Consider next example where res/values/strings.xml has following definition: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">hello, World!</string>

31 </resources> Now you can set the text on a TextView object with ID msg using a resource ID as follows: TextView msgtextview = (TextView) findviewbyid(r.id.msg); msgtextview.settext(r.string.hello); EXAMPLE: Consider a layout res/layout/activity_main.xml with the following definition: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello, I am a TextView" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello, I am a Button" /> </LinearLayout> This application code will load this layout for an Activity, in the oncreate() method as follows: public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main_activity); ACCESSING RESOURCES IN XML Consider the following resource XML res/values/strings.xml file that includes a color resource and a string resource: <?xml version="1.0" encoding="utf-8"?> <resources> <color name="opaque_red">#f00</color> <string name="hello">hello!</string> </resources> Now you can use these resources in the following layout file to set the text color and text string as follows: <?xml version="1.0" encoding="utf-8"?> <EditText xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:textcolor="@color/opaque_red" android:text="@string/hello" /> Now if you will go through previous chapter once again where I have explained Hello World! example, and I'm sure you will have better understanding on all the concepts explained in this chapter. So I highly recommend to check previous chapter for working example and check how I have used various resources at very basic level.

32 CHAPTER 7 Activities An activity represents a single screen with a user interface. For example, an application might have one activity that shows a list of new s, another activity to compose an , and another activity for reading s. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched. If you have worked with C, C++ or Java programming language then you must have seen that your program starts from main() function. Very similar way, Android system initiates its program with in anactivity starting with a call on oncreate() callback method. There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity as shown in the below Activity lifecycle diagram: (image courtesy : android.com ) The Activity class defines the following callbacks i.e. events. You don't need to implement all the callbacks methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect. Callback oncreate() onstart() onresume() Description This is the first callback and called when the activity is first created. This callback is called when the activity becomes visible to the user. This is called when the user starts interacting with the application.

33 onpause() onstop() ondestroy() The paused activity does not receive user input and cannot execute any code and called when the current activity is being paused and the previous activity is being resumed. This callback is called when the activity is no longer visible. This callback is called before the activity is destroyed by the system. onrestart() Example This callback is called when the activity restarts after stopping it. This example will take you through simple steps to show Android application activity life cycle. Follow the following steps to modify the Android application we created in Hello World Example chapter: Step Description 1 You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. 2 Modify main activity file MainActivity.java as explained below. Keep rest of the files unchanged. 3 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.helloworld/mainactivity.java. This file includes each of the fundamental lifecycle methods. The Log.d() method has been used to generate log messages: package com.example.helloworld; import android.os.bundle; import android.app.activity; import android.util.log; public class MainActivity extends Activity { String msg = "Android : "; /** Called when the activity is first created. public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); Log.d(msg, "The oncreate() event"); /** Called when the activity is about to become visible. protected void onstart() { super.onstart(); Log.d(msg, "The onstart() event"); /** Called when the activity has become visible. protected void onresume() { super.onresume(); Log.d(msg, "The onresume() event"); /** Called when another activity is taking focus.

34 protected void onpause() { super.onpause(); Log.d(msg, "The onpause() event"); /** Called when the activity is no longer visible. protected void onstop() { super.onstop(); Log.d(msg, "The onstop() event"); /** Called just before the activity is destroyed. public void ondestroy() { super.ondestroy(); Log.d(msg, "The ondestroy() event"); An activity class loads all the UI component using the XML file available in res/layout folder of the project. Following statement loads UI components from res/layout/activity_main.xml file: setcontentview(r.layout.activity_main); An application can have one or more activities without any restrictions. Every activity you define for your application must be declared in your AndroidManifest.xml file and the main activity for your app must be declared in the manifest with an <intent-filter> that includes the MAIN action and LAUNCHER category as follows: <manifest xmlns:android=" package="com.example.helloworld" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name=".mainactivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher"/> </intent-filter> </activity> </application> </manifest> If either the MAIN action or LAUNCHER category are not declared for one of your activities, then your app icon will not appear in the Home screen's list of apps. Let's try to run our modified Hello World! application we just modified. I assume you had created youravd while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display Emulator window and you should see following log messages in LogCat window in Eclipse IDE: :00:43.405: D/Android :(866): The oncreate() event

35 :00:43.405: D/Android :(866): The onstart() event :00:43.415: D/Android :(866): The onresume() event Let us try to click Red button in LogCat window in Eclipse IDE: on the Android emulator and it will generate following events messages :01:10.995: D/Android :(866): The onpause() event :01:12.705: D/Android :(866): The onstop() event Let us again try to click Menu button in LogCat window in Eclipse IDE: on the Android emulator and it will generate following events messages :01:13.995: D/Android :(866): The onstart() event :01:14.705: D/Android :(866): The onresume() event Next, let us again try to click Back button on the Android emulator and it will generate following events messages in LogCat window in Eclipse IDE and this completes the Acitivity Life Cycle for an Android Application :33:15.687: D/Android :(992): The onpause() event :33:15.525: D/Android :(992): The onstop() event :33:15.525: D/Android :(992): The ondestroy() event

36 CHAPTER 8 Services Aservice is a component that runs in the background to perform long-running operations without needing to interact with the user. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity. A service can essentially take two states: State Started Bound Description A service is started when an application component, such as an activity, starts it by calling startservice(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. A service is bound when an application component binds to it by callingbindservice(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A service has lifecycle callback methods that you can implement to monitor changes in the service's state and you can perform work at the appropriate stage. The following diagram on the left shows the lifecycle when the service is created with startservice() and the diagram on the right shows the lifecycle when the service is created with bindservice(): (image courtesy : android.com )

37 To create an service, you create a Java class that extends the Service base class or one of its existing subclasses. The Service base class defines various callback methods and the most important are given below. You don't need to implement all the callbacks methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect. Callback onstartcommand() onbind() onunbind() onrebind() Description The system calls this method when another component, such as an activity, requests that the service be started, by calling startservice(). If you implement this method, it is your responsibility to stop the service when its work is done, by calling stopself() or stopservice() methods. The system calls this method when another component wants to bind with the service by calling bindservice(). If you implement this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder object. You must always implement this method, but if you don't want to allow binding, then you should return null. The system calls this method when all clients have disconnected from a particular interface published by the service. The system calls this method when new clients have connected to the service, after it had previously been notified that all had disconnected in itsonunbind(intent).

38 oncreate() ondestroy() The system calls this method when the service is first created usingonstartcommand() or onbind(). This call is required to perform one-time setup. The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc. The following skeleton service demonstrates each of the lifecycle methods: package com.tutorialspoint; import android.app.service; import android.os.ibinder; import android.content.intent; import android.os.bundle; public class HelloService extends Service { /** indicates how to behave if the service is killed */ int mstartmode; /** interface for clients that bind */ IBinder mbinder; /** indicates whether onrebind should be used */ boolean mallowrebind; /** Called when the service is being created. public void oncreate() { /** The service is starting, due to a call to startservice() public int onstartcommand(intent intent, int flags, int startid) { return mstartmode; /** A client is binding to the service with bindservice() public IBinder onbind(intent intent) { return mbinder; /** Called when all clients have unbound with unbindservice() public boolean onunbind(intent intent) { return mallowrebind; /** Called when a client is binding to the service with public void onrebind(intent intent) { /** Called when The service is no longer used and is being destroyed public void ondestroy() {

39 Example This example will take you through simple steps to show how to create your own Android Service. Follow the following steps to modify the Android application we created in Hello World Examplechapter: Step 1 Description You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. 2 Modify main activity file MainActivity.java to add startservice() and stopservice() methods. 3 4 Create a new java file MyService.java under the package com.example.helloworld. This file will have implementation of Android service related methods. Define your service in AndroidManifest.xml file using <service.../> tag. An application can have one or more services without any restrictions. 5 Modify the detault content of res/layout/activity_main.xml file to include two buttons in linear layout. 6 Define two constants start_service and stop_service in res/values/strings.xml file 7 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.helloworld/mainactivity.java. This file can include each of the fundamental lifecycle methods. We have added startservice() and stopservice() methods to start and stop the service. package com.example.helloworld; import android.os.bundle; import android.app.activity; import android.view.menu; import android.content.intent; import android.view.view; public class MainActivity extends Activity public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.activity_main, menu); return true; // Method to start the service public void startservice(view view) { startservice(new Intent(getBaseContext(), MyService.class)); // Method to stop the service public void stopservice(view view) { stopservice(new Intent(getBaseContext(), MyService.class));

40 Following is the content of src/com.example.helloworld/myservice.java. This file can have implementation of one or more methods associated with Service based on requirements. For now we are going to implement only two methods onstartcommand() and ondestroy(): package com.example.helloworld; import android.app.service; import android.content.intent; import android.os.ibinder; import android.widget.toast; public class MyService extends Service public IBinder onbind(intent arg0) { return public int onstartcommand(intent intent, int flags, int startid) { // Let it continue running until it is stopped. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); return public void ondestroy() { super.ondestroy(); Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); Following will the modified content of AndroidManifest.xml file. Here we have added <service.../> tag to include our service: <manifest xmlns:android=" package="com.example.helloworld" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name=".mainactivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher"/> </intent-filter> </activity> <service android:name=".myservice" /> </application> </manifest> Following will be the content of res/layout/activity_main.xml file to include two buttons:

41 <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:onclick="startservice"/> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:onclick="stopservice" /> </LinearLayout> Following will be the content of res/values/strings.xml to define two new constants: <resources> <string name="app_name">helloworld</string> <string name="hello_world">hello world!</string> <string name="menu_settings">settings</string> <string name="title_activity_main">mainactivity</string> <string name="start_service">start Service</string> <string name="stop_service">stop Service</string> </resources> Let's try to run our modified Hello World! application we just modified. I assume you had created youravd while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

42 Now to start your service, let's click on Start Service button, this will start the service and as per our programming in onstartcommand() method, a message Service Started will appear on the bottom of the the simulator as follows:

43 To stop the service, you can click the Stop Service button.

44 CHAPTER 9 Broadcast Recievers Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself. These messages are sometime called events or intents. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action. There are following two important steps to make BroadcastReceiver works for the systen broadcasted intents: Creating the Broadcast Receiver. Registering Broadcast Receiver There is one additional steps in case you are going to implement your custom intents then you will have to create and broadcast those intents. Creating the Broadcast Receiver A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the onreceive() method where each message is received as a Intent object parameter. public class MyReceiver extends BroadcastReceiver public void onreceive(context context, Intent intent) { Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show(); Registering Broadcast Receiver An application listens for specific broadcast intents by registering a broadcast receiver inandroidmanifest.xml file. Consider we are going to register MyReceiver for system generated event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has completed the boot process. <application android:icon="@drawable/ic_launcher"

45 > <receiver android:name="myreceiver"> <intent-filter> <action android:name="android.intent.action.boot_completed"> </action> </intent-filter> </receiver> </application> Now whenever your Android device gets booted, it will be intercepted by BroadcastReceiver MyReceiverand implemented logic inside onreceive() will be executed. There are several system generated events defined as final static fields in the Intent class. The following table lists a few important system events. Event Constant android.intent.action.battery_changed android.intent.action.battery_low android.intent.action.battery_okay android.intent.action.boot_completed android.intent.action.bug_report android.intent.action.call android.intent.action.call_button android.intent.action.date_changed Description Sticky broadcast containing the charging state, level, and other information about the battery. Indicates low battery condition on the device. Indicates the battery is now okay after being low. This is broadcast once, after the system has finished booting. Show activity for reporting a bug. Perform a call to someone specified by the data. The user pressed the "call" button to go to the dialer or other appropriate UI for placing a call. The date has changed. android.intent.action.reboot Broadcasting Custom Intents Have the device reboot. If you want your application itself should generate and send custom intents then you will have to create and send those intents by using the sendbroadcast() method inside your activity class. If you use thesendstickybroadcast(intent) method, the Intent is sticky, meaning the Intent you are sending stays around after the broadcast is complete. public void broadcastintent(view view) { Intent intent = new Intent(); intent.setaction("com.tutorialspoint.custom_intent"); sendbroadcast(intent); This intent com.tutorialspoint.custom_intent can also be regsitered in similar way as we have regsitered system generated intent. <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" >

46 <receiver android:name="myreceiver"> <intent-filter> <action android:name="com.tutorialspoint.custom_intent"> </action> </intent-filter> </receiver> </application> Example This example will explain you how to create BroadcastReceiver to intercept custom intent. Once you are familiar with custom intent, then you can program your application to intercept system generated intents. So let's follow the following steps to modify the Android application we created in Hello World Example chapter: Step Description 1 You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. 2 Modify main activity file MainActivity.java to add broadcastintent() method. 3 4 Create a new java file called MyReceiver.java under the package com.example.helloworld to define a BroadcastReceiver. An application can handle one or more custom and system intents without any restrictions. Every indent you want to intercept must be registered in your AndroidManifest.xml file using <receiver.../> tag 5 Modify the detault content of res/layout/activity_main.xml file to include a button to broadcast intent. 6 Define a constant broadcast_intent in res/values/strings.xml file 7 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.helloworld/mainactivity.java. This file can include each of the fundamental lifecycle methods. We have added broadcastintent() method to broadcast a custom intent. package com.example.helloworld; import android.os.bundle; import android.app.activity; import android.view.menu; import android.content.intent; import android.view.view; public class MainActivity extends Activity public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.activity_main, menu); return true; // broadcast a custom intent. public void broadcastintent(view view)

47 { Intent intent = new Intent(); intent.setaction("com.tutorialspoint.custom_intent"); sendbroadcast(intent); Following is the content of src/com.example.helloworld/myreceiver.java: package com.example.helloworld; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.widget.toast; public class MyReceiver extends BroadcastReceiver public void onreceive(context context, Intent intent) { Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show(); Following will the modified content of AndroidManifest.xml file. Here we have added <service.../> tag to include our service: <manifest xmlns:android=" package="com.example.helloworld" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name=".mainactivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher"/> </intent-filter> </activity> <receiver android:name="myreceiver"> <intent-filter> <action android:name="com.tutorialspoint.custom_intent"> </action> </intent-filter> </receiver> </application> </manifest> Following will be the content of res/layout/activity_main.xml file to include a button to broadcast our custom intent: <LinearLayout xmlns:android="

48 android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:onclick="broadcastintent"/> </LinearLayout> Following will be the content of res/values/strings.xml to define two new constants: <resources> <string name="app_name">helloworld</string> <string name="hello_world">hello world!</string> <string name="menu_settings">settings</string> <string name="title_activity_main">mainactivity</string> <string name="broadcast_intent">broadcast Intent</string> </resources> Let's try to run our modified Hello World! application we just modified. I assume you had created youravd while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

49 Now to broadcast our custom intent, let's click on Broadcast Intent button, this will broadcast our custom intent "com.tutorialspoint.custom_intent" which will be intercepted by our registered BroadcastReceiver ie. MyReceiver and as per our implemented logic a toast will appear on the bottom of the the simulator as follows:

50 You can try implementing other BroadcastReceiver to intercept system generated intents like system bootup, date changed, low battery etc.

51 CHAPTER 10 Content Providers A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. A content provider can use different ways to store its data and the data can be stored in a database, in files, or even over a network. Each Android applications runs in its own process with its own permissions which keeps an application data hidden from another application. But sometimes it is required to share data across applications. This is where content providers become very useful. Content providers let you centralize content in one place and have many different applications access it as needed. A content provider behaves very much like a database where you can query it, edit its content, as well as add or delete content usingg insert(), update(), delete(), and query() methods. In most cases this data is stored in an SQlite database. A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions. public class MyContentProvider extends ContentProvider { Content URIs To query a content provider, you specify the query string in the form of a URI which has following format: <prefix>://<authority>/<data_type>/<id> Here is the detaial of various parts of the URI: Part prefix authority data_type Id Description This is always set to content:// This specifies the name of the content provider, for example contacts, browser etc. For third-party content providers, this could be the fully qualified name, such ascom.tutorialspoint.statusprovider This indicates the type of data that this particular provider provides. For example, if you are getting all the contacts from the Contacts content provider, then the data path would be people and URI would look like this content://contacts/people This specifies the specific record requested. For example, if you are looking for contact number 5 in the Contacts content provider then URI would look like thiscontent://contacts/people/5.

52 Create Content Provider This involves number of simple steps to create your own content provider. First of all you need to create a Content Provider class that extends the ContentProviderbaseclass. Second, you need to define your content provider URI address which will be used to access the content. Next you will need to create your own database to keep the content. Usually, Android uses SQLite database and framework needs to override oncreate() method which will use SQLite Open Helper method to create or open the provider's databse. When your application is launched, theoncreate() handler of each of its Content Providers is called on the main application thread. Next you will have to implement Content Provider queries to perform different database specific operations. Finally register your Content Provider in your acitivity file using <provider> tag. Here is the list of methods which you need to override in Content Provider class to have your Content Provider working: oncreate() This method is called when the provider is started. query() This method receives a request from a client. The result is returned as a Cursor object. insert()this method inserts a new record into the content provider. delete() This method deletes an existing record from the content provider. update() This method updates an existing record from the content provider. gettype() This method returns the MIME type of the data at the given URI. Example This example will explain you how to create your own ContentProvider. So let's follow the following steps to similar to what we followed while creating Hello World Example: Step Description You will use Eclipse IDE to create an Android application and name it as MyContentProviderunder a package com.example.mycontentprovider, with blank Activity. Modify main activity file MainActivity.java to add two new methods onclickaddname() andonclickretrievestudents(). Create a new java file called StudentsProvider.java under the packagecom.example.mycontentprovider to define your actual provider and associated methods. 4 Register your content provider in your AndroidManifest.xml file using <provider.../> tag 5 Modify the detault content of res/layout/activity_main.xml file to include a small GUI to add sudents records. 6 Define required constants in res/values/strings.xml file 7 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.mycontentprovider/mainactivity.java. This file can include each of the fundamental lifecycle methods. We have added two new methods onclickaddname() andonclickretrievestudents() to handle user interaction with the application. package com.example.mycontentprovider;

53 import android.net.uri; import android.os.bundle; import android.app.activity; import android.content.contentvalues; import android.content.cursorloader; import android.database.cursor; import android.view.menu; import android.view.view; import android.widget.edittext; import android.widget.toast; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; public void onclickaddname(view view) { // Add a new student record ContentValues values = new ContentValues(); values.put(studentsprovider.name, ((EditText)findViewById(R.id.txtName)).getText().toString()); values.put(studentsprovider.grade, ((EditText)findViewById(R.id.txtGrade)).getText().toString()); Uri uri = getcontentresolver().insert( StudentsProvider.CONTENT_URI, values); Toast.makeText(getBaseContext(), uri.tostring(), Toast.LENGTH_LONG).show(); public void onclickretrievestudents(view view) { // Retrieve student records String URL = "content://com.example.provider.college/students"; Uri students = Uri.parse(URL); Cursor c = managedquery(students, null, null, null, "name"); if (c.movetofirst()) { do{ Toast.makeText(this, c.getstring(c.getcolumnindex(studentsprovider._id)) + ", " + c.getstring(c.getcolumnindex( StudentsProvider.NAME)) + ", " + c.getstring(c.getcolumnindex( StudentsProvider.GRADE)), Toast.LENGTH_SHORT).show(); while (c.movetonext());

54 Create new file StudentsProvider.java under com.example.mycontentprovider package and following is the content of src/com.example.mycontentprovider/studentsprovider.java: package com.example.mycontentprovider; import java.util.hashmap; import android.content.contentprovider; import android.content.contenturis; import android.content.contentvalues; import android.content.context; import android.content.urimatcher; import android.database.cursor; import android.database.sqlexception; import android.database.sqlite.sqlitedatabase; import android.database.sqlite.sqliteopenhelper; import android.database.sqlite.sqlitequerybuilder; import android.net.uri; import android.text.textutils; public class StudentsProvider extends ContentProvider { static final String PROVIDER_NAME = "com.example.provider.college"; static final String URL = "content://" + PROVIDER_NAME + "/students"; static final Uri CONTENT_URI = Uri.parse(URL); static final String _ID = "_id"; static final String NAME = "name"; static final String GRADE = "grade"; private static HashMap<String, String> STUDENTS_PROJECTION_MAP; static final int STUDENTS = 1; static final int STUDENT_ID = 2; static final UriMatcher urimatcher; static{ urimatcher = new UriMatcher(UriMatcher.NO_MATCH); urimatcher.adduri(provider_name, "students", STUDENTS); urimatcher.adduri(provider_name, "students/#", STUDENT_ID); /** * Database specific constant declarations */ private SQLiteDatabase db; static final String DATABASE_NAME = "College"; static final String STUDENTS_TABLE_NAME = "students"; static final int DATABASE_VERSION = 1; static final String CREATE_DB_TABLE = " CREATE TABLE " + STUDENTS_TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + " name TEXT NOT NULL, " + " grade TEXT NOT NULL);"; /** * Helper class that actually creates and manages * the provider's underlying data repository. */ private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context){

55 super(context, DATABASE_NAME, null, public void oncreate(sqlitedatabase db) { public void onupgrade(sqlitedatabase db, int oldversion, int newversion) { db.execsql("drop TABLE IF EXISTS " + STUDENTS_TABLE_NAME); public boolean oncreate() { Context context = getcontext(); DatabaseHelper dbhelper = new DatabaseHelper(context); /** * Create a write able database which will trigger its * creation if it doesn't already exist. */ db = dbhelper.getwritabledatabase(); return (db == null)? public Uri insert(uri uri, ContentValues values) { /** * Add a new student record */ long rowid = db.insert( STUDENTS_TABLE_NAME, "", values); /** * If record is added successfully */ if (rowid > 0) { Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowid); getcontext().getcontentresolver().notifychange(_uri, null); return _uri; throw new SQLException("Failed to add a record into " + public Cursor query(uri uri, String[] projection, String selection, String[] selectionargs, String sortorder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.settables(students_table_name); switch (urimatcher.match(uri)) { case STUDENTS: qb.setprojectionmap(students_projection_map); break; case STUDENT_ID: qb.appendwhere( _ID + "=" + uri.getpathsegments().get(1)); break;

56 default: throw new IllegalArgumentException("Unknown URI " + uri); if (sortorder == null sortorder == ""){ /** * By default sort on student names */ sortorder = NAME; Cursor c = qb.query(db, projection, selection, selectionargs, null, null, sortorder); /** * register to watch a content URI for changes */ c.setnotificationuri(getcontext().getcontentresolver(), uri); return public int delete(uri uri, String selection, String[] selectionargs) { int count = 0; switch (urimatcher.match(uri)){ case STUDENTS: count = db.delete(students_table_name, selection, selectionargs); break; case STUDENT_ID: String id = uri.getpathsegments().get(1); count = db.delete( STUDENTS_TABLE_NAME, _ID + " = " + id + (!TextUtils.isEmpty(selection)? " AND (" + selection + ')' : ""), selectionargs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); getcontext().getcontentresolver().notifychange(uri, null); return public int update(uri uri, ContentValues values, String selection, String[] selectionargs) { int count = 0; switch (urimatcher.match(uri)){ case STUDENTS: count = db.update(students_table_name, values, selection, selectionargs); break; case STUDENT_ID: count = db.update(students_table_name, values, _ID + " = " + uri.getpathsegments().get(1) + (!TextUtils.isEmpty(selection)? " AND (" + selection + ')' : ""), selectionargs); break; default: throw new IllegalArgumentException("Unknown URI " + uri ); getcontext().getcontentresolver().notifychange(uri, null);

57 return public String gettype(uri uri) { switch (urimatcher.match(uri)){ /** * Get all student records */ case STUDENTS: return "vnd.android.cursor.dir/vnd.example.students"; /** * Get a particular student */ case STUDENT_ID: return "vnd.android.cursor.item/vnd.example.students"; default: throw new IllegalArgumentException("Unsupported URI: " + uri); Following will the modified content of AndroidManifest.xml file. Here we have added <provider.../> tag to include our content provider: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.mycontentprovider" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="com.example.mycontentprovider.mainactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <provider android:name="studentsprovider" android:authorities="com.example.provider.college"> </provider> </application> </manifest> Following will be the content of res/layout/activity_main.xml file to include a button to broadcast your custom intent: <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent"

58 android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="name" /> <EditText android:layout_height="wrap_content" android:layout_width="fill_parent" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="grade" /> <EditText android:layout_height="wrap_content" android:layout_width="fill_parent" /> <Button android:text="add Name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onclick="onclickaddname" /> <Button android:text="retrieve Students" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onclick="onclickretrievestudents" /> </LinearLayout> Make sure you have following content of res/values/strings.xml file: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">mycontentprovider</string> <string name="action_settings">settings</string> <string name="hello_world">hello world!</string> </resources>; Let's try to run our modified MyContentProvider application we just created. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window, be patience because it may take sometime based on your computer speed:

59 Now let's enter student Name and Grade and finally click on Add Name button, this will add student record in the database and will flash a message at the bottom showing ContentProvider URI along with record number added in the database. This operation makes use of our insert() method. Let's repeat this process to add few more students in the database of our content provider.

60 Once you are done with adding records in the database, now its time to ask ContentProvider to give us those records back, so let's click Retrieve Students button which will fetch and display all the records one by one which is as per our the implementation of our query() method.

61 You can write activities against update and delete operations by providing callback functions inmainactivity.java file and then modify user interface to have buttons for update and deleted operations in the same way as we have done for add and read operations. This way you can use existing Content Provider like Address Book or you can use Content Provider concept in developing nice database oriented applications where you can perform all sort of database operations like read, write, update and delete as explained above in the example.

62 CHAPTER 11 Fragments A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity which enable more modular activity design. It will not be wrong if we say, a fragment is a kind of sub-acitivity. Following are important points about fragment: A fragment has its own layout and its own behavior with its own lifecycle callbacks. You can add or remove fragments in an activity while the activity is running. You can combine multiple fragments in a single activity to build a multi-pane UI. A fragment can be used in multiple activities. Fragment life cycle is closely related to the lifecycle of its host activity which means when the activity is paused, all the fragments available in the acivity will also be stopped. A fragment can implement a behavior that has no user interface component. Fragments were added to the Android API in Honeycomb version of Android which API version 11. You create fragments by extending Fragment class and You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element. Prior to fragment introduction, we had a limitation because we can show only a single activity on the screen at one given point in time. So we were not able to divide device screen and control different parts separately. But with the introduction of fragment we got more flexibility and removed the limitation of having a single activity on the screen at a time. Now we can have a single acitivity but each acitivity can comprise of multiple fragments which will have their own layout, events and complete lifecycle. Following is a typical example of how two UI modules defined by fragments can be combined into one activity for a tablet design, but separated for a handset design.

63 The application can embed two fragments in Activity A, when running on a tablet-sized device. However, on a handset-sized screen, there's not enough room for both fragments, so Activity A includes only the fragment for the list of articles, and when the user selects an article, it starts Activity B, which includes the second fragment to read the article. Fragment Life Cycle Android fragments have their own life cycle very similar to an android activity. This section briefs different stages of its life cycle.

64 Phase I: When a fragment gets created, it goes through the following states: onattach() oncreate() oncreateview() onactivitycreated() Phase II: When the fragment becomes visible, it goes through these states: onstart() onresume() Phase III: When the fragment goes into the background mode, it goes through these states: onpaused() onstop() Phase IV: When the fragment is destroyed, it goes through the following states: onpaused() onstop() ondestroyview() ondestroy() ondetach() How to use Fragments? This involves number of simple steps to create Fragments. First of all decide how many fragments you want to use in an activity. Fors example let's we want to use two fragments to handle landscape and portrait modes of the device. Next based on number of fragments, create classes which will extend the Fragment class. The Fragment class has above mentioned callback functions. You can override any of the functions based on your requirements. Corresponding to each fragment, you will need to create layout files in XML file. These files will have layout for the defined fragments. Finally modify activity file to define the actual logic of replacing fragments based on your requirement.

65 Here is the list of important methods which you can to override in your fragment class: oncreate() The system calls this when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed. oncreateview() The system calls this callback when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI. onpause() The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session. Example This example will explain you how to create your own Fragments. Here we will create two fragments and one of them will be used when device is in landscape mode and another fragment will be used in case of portrait mode. So let's follow the following steps to similar to what we followed while creatinghello World Example: Step Description You will use Eclipse IDE to create an Android application and name it as MyFragments under a package com.example.myfragments, with blank Activity. Modify main activity file MainActivity.java as shown below in the code. Here we will check orientation of the device and accordingly we will switch between different fragments. Create a two java files PM_Fragment.java and LM_Fragement.java under the packagecom.example.myfragments to define your fragments and associated methods. Create layouts files res/layout/lm_fragment.xml and res/layout/pm_fragment.xml and define your layouts for both the fragments.< 5 Modify the detault content of res/layout/activity_main.xml file to include both the fragments. 6 Define required constants in res/values/strings.xml file 7 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.mycontentprovider/mainactivity.java: package com.example.myfragments; import android.os.bundle; import android.app.activity; import android.app.fragmentmanager; import android.app.fragmenttransaction; import android.content.res.configuration; import android.view.windowmanager; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); Configuration config = getresources().getconfiguration(); FragmentManager fragmentmanager = getfragmentmanager(); FragmentTransaction fragmenttransaction = fragmentmanager.begintransaction(); /** * Check the device orientation and act accordingly

66 */ if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) { /** * Landscape mode of the device */ LM_Fragment ls_fragment = new LM_Fragment(); fragmenttransaction.replace(android.r.id.content, ls_fragment); else{ /** * Portrait mode of the device */ PM_Fragment pm_fragment = new PM_Fragment(); fragmenttransaction.replace(android.r.id.content, pm_fragment); fragmenttransaction.commit(); Create two fragment files LM_Fragement.java and PM_Fragment.java undercom.example.mycontentprovider package. Following is the content of LM_Fragement.java file: package com.example.myfragments; import android.app.fragment; import android.os.bundle; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; public class LM_Fragment extends public View oncreateview(layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) { /** * Inflate the layout for this fragment */ return inflater.inflate( R.layout.lm_fragment, container, false); Following is the content of PM_Fragement.java file: package com.example.myfragments; import android.app.fragment; import android.os.bundle; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; public class PM_Fragment extends public View oncreateview(layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) { /**

67 * Inflate the layout for this fragment */ return inflater.inflate( R.layout.pm_fragment, container, false); Create two layout files lm_fragement.xml and pm_fragment.xml under res/layout directory. Following is the content of lm_fragement.xml file: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#7bae16"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textcolor="#000000" android:textsize="20px" /> <!-- More GUI components go here --> </LinearLayout> Following is the content of pm_fragment.xml file: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#666666"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textcolor="#000000" android:textsize="20px" /> <!-- More GUI components go here --> </LinearLayout> Following will be the content of res/layout/activity_main.xml file which includes your fragments: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal"> <fragment

68 android:name="com.example.fragments" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="com.example.fragments" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout> Make sure you have following content of res/values/strings.xml file: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">myfragments</string> <string name="action_settings">settings</string> <string name="hello_world">hello world!</string> <string name="landscape_message">this is Landscape mode fragment </string> <string name="portrait_message">this is Portrait mode fragment </string> </resources> Let's try to run our modified MyFragments application we just created. I assume you had created youravd while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display Emulator window where you will click on Menu button to see the following window. Be patience because it may take sometime based on your computer speed:

69 To change the mode of the emulator screen, let's do the following: fn+control+f11 on Mac to change the landscape to portrait and vice versa. ctrl+f11 on Windows. ctrl+f11 on Linux. Once you changed the mode, you will be able to see the GUI which you have implemented for landscape mode as below:

70 This way you can use same activity but different GUIs through different fragments. You can use different type of GUI components for different GUIs based on your requirements.

71 CHAPTER 12 Intents and Filters An Android Intent is an object carrying an intent ie. message from one component to another component with-in the application or outside the application. The intents can communicate messages among any of the three core components of an application - activities, services, and broadcast receivers. The intent itself, an Intent object, is a passive data structure holding an abstract description of an operation to be performed. For example, let's assume that you have an Activity that needs to launch an client and sends an using your Android device. For this purpose, your Activity would send an ACTION_SEND along with appropriate chooser, to the Android Intent Resolver. The specified chooser gives the proper interface for the user to pick how to send your data. For example, assume that you have an Activity that needs to open URL in a web browser on your Android device. For this purpose, your Activity will send ACTION_WEB_SEARCH Intent to the Android Intent Resolver to open given URL in the web browser. The Intent Resolver parses through a list of Activities and chooses the one that would best match your Intent, in this case, the Web Browser Activity. The Intent Resolver then passes your web page to the web browser and starts the Web Browser Activity. There are separate mechanisms for delivering intents to each type of component - activities, services, and broadcast receivers. S.N. 1 2 Method & Description Context.startActivity() The Intent object is passed to this method to launch a new activity or get an existing activity to do something new. Context.startService() The Intent object is passed to this method to initiate a service or deliver new instructions to an ongoing service. 3 Context.sendBroadcast() The Intent object is passed to this method to deliver the message to all interested broadcast receivers. Intent Objects An Intent object is a bundle of information which is used by the component that receives the intent plus information used by the Android system. An Intent object can contain the following components based on what it is communicating or going to perform:

72 ACTION This is mandatory part of the Intent object and is a string naming the action to be performed or, in the case of broadcast intents, the action that took place and is being reported. The action largely determines how the rest of the intent object is structured. The Intent class defines a number of action constants corresponding to different intents. Here is a list of Android Intent Standard Actions Android Intent Standard Actions: Following table lists down various important Android Intent Standard Actions. You can check Android Official Documentation for a complete list of Actions: S.N Activity Action Intent & Description ACTION_ALL_APPS List all the applications available on the device. ACTION_ANSWER Handle an incoming phone call. ACTION_ATTACH_DATA Used to indicate that some piece of data should be attached to some other place ACTION_BATTERY_CHANGED This is a sticky broadcast containing the charging state, level, and other information about the battery. ACTION_BATTERY_LOW This broadcast corresponds to the "Low battery warning" system dialog. ACTION_BATTERY_OKAY This will be sent after ACTION_BATTERY_LOW once the battery has gone back up to an okay state. ACTION_BOOT_COMPLETED This is broadcast once, after the system has finished booting. ACTION_BUG_REPORT Show activity for reporting a bug. ACTION_CALL Perform a call to someone specified by the data. ACTION_CALL_BUTTON The user pressed the "call" button to go to the dialer or other appropriate UI for placing a call. ACTION_CAMERA_BUTTON The "Camera Button" was pressed. ACTION_CHOOSER Display an activity chooser, allowing the user to pick what they want to before proceeding. ACTION_CONFIGURATION_CHANGED The current device Configuration (orientation, locale, etc) has changed. ACTION_DATE_CHANGED The date has changed. ACTION_DEFAULT A synonym for ACTION_VIEW, the "standard" action that is performed on a piece of data.

73 ACTION_DELETE Delete the given data from its container. ACTION_DEVICE_STORAGE_LOW A sticky broadcast that indicates low memory condition on the device. ACTION_DEVICE_STORAGE_OK Indicates low memory condition on the device no longer exists. ACTION_DIAL Dial a number as specified by the data. ACTION_DOCK_EVENT A sticky broadcast for changes in the physical docking state of the device. ACTION_DREAMING_STARTED Sent after the system starts dreaming. ACTION_DREAMING_STOPPED Sent after the system stops dreaming. ACTION_EDIT Provide explicit editable access to the given data. ACTION_FACTORY_TEST Main entry point for factory tests. ACTION_GET_CONTENT Allow the user to select a particular kind of data and return it. ACTION_GTALK_SERVICE_CONNECTED A GTalk connection has been established. ACTION_GTALK_SERVICE_DISCONNECTED A GTalk connection has been disconnected. ACTION_HEADSET_PLUG Wired Headset plugged in or unplugged. ACTION_INPUT_METHOD_CHANGED An input method has been changed. ACTION_INSERT Insert an empty item into the given container. ACTION_INSERT_OR_EDIT Pick an existing item, or insert a new item, and then edit it. ACTION_INSTALL_PACKAGE Launch application installer. ACTION_LOCALE_CHANGED The current device's locale has changed. ACTION_MAIN Start as a main entry point, does not expect to receive data. ACTION_MEDIA_BUTTON The "Media Button" was pressed.

74 ACTION_MEDIA_CHECKING External media is present, and being disk-checked. ACTION_MEDIA_EJECT User has expressed the desire to remove the external storage media. ACTION_MEDIA_REMOVED External media has been removed. ACTION_NEW_OUTGOING_CALL An outgoing call is about to be placed. ACTION_PASTE Create a new item in the given container, initializing it from the current contents of the clipboard. ACTION_POWER_CONNECTED External power has been connected to the device. ACTION_REBOOT Have the device reboot. This is only for use by system code. ACTION_RUN Run the data, whatever that means. ACTION_SCREEN_OFF Sent after the screen turns off. ACTION_SCREEN_ON Sent after the screen turns on. ACTION_SEARCH Perform a search. ACTION_SEND Deliver some data to someone else. ACTION_SENDTO Send a message to someone specified by the data. ACTION_SEND_MULTIPLE Deliver multiple data to someone else. ACTION_SET_WALLPAPER Show settings for choosing wallpaper. ACTION_SHUTDOWN Device is shutting down. ACTION_SYNC Perform a data synchronization. ACTION_TIMEZONE_CHANGED The timezone has changed. ACTION_TIME_CHANGED The time was set. ACTION_VIEW Display the data to the user.

75 ACTION_VOICE_COMMAND Start Voice Command. ACTION_WALLPAPER_CHANGED The current system wallpaper has changed. ACTION_WEB_SEARCH Perform a web search. The action in an Intent object can be set by the setaction() method and read by getaction(). DATA The URI of the data to be acted on and the MIME type of that data. For example, if the action field is ACTION_EDIT, the data field would contain the URI of the document to be displayed for editing. The setdata() method specifies data only as a URI, settype() specifies it only as a MIME type, and setdataandtype() specifies it as both a URI and a MIME type. The URI is read by getdata() and the type by gettype(). Some examples of action/data pairs are: S.N Action/Data Pair & Description ACTION_VIEW content://contacts/people/1 Display information about the person whose identifier is "1". ACTION_DIAL content://contacts/people/1 Display the phone dialer with the person filled in. ACTION_VIEW tel:123 Display the phone dialer with the given number filled in. ACTION_DIAL tel:123 Display the phone dialer with the given number filled in. ACTION_EDIT content://contacts/people/1 Edit information about the person whose identifier is "1". 6 ACTION_VIEW content://contacts/people/ Display a list of people, which the user can browse through. CATEGORY The category is an optional part of Intent object and it's a string containing additional information about the kind of component that should handle the intent. The addcategory() method places a category in an Intent object, removecategory() deletes a category previously added, and getcategories() gets the set of all categories currently in the object. Here is a list of Android Intent Standard Categories. Android Intent Standard Categories Following table lists down various important Android Intent Standard Categories. You can check Android Official Documentation for a complete list of Categories: S.N. Categories & Description 1 CATEGORY_APP_BROWSER

76 Used with ACTION_MAIN to launch the browser application CATEGORY_APP_CALCULATOR Used with ACTION_MAIN to launch the calculator application. CATEGORY_APP_CALENDAR Used with ACTION_MAIN to launch the calendar application. CATEGORY_APP_CONTACTS Used with ACTION_MAIN to launch the contacts application. CATEGORY_APP_ Used with ACTION_MAIN to launch the application. CATEGORY_APP_GALLERY Used with ACTION_MAIN to launch the gallery application. CATEGORY_APP_MAPS Used with ACTION_MAIN to launch the maps application. CATEGORY_APP_MARKET This activity allows the user to browse and download new applications. CATEGORY_APP_MESSAGING Used with ACTION_MAIN to launch the messaging application. CATEGORY_APP_MUSIC Used with ACTION_MAIN to launch the music application. CATEGORY_BROWSABLE Activities that can be safely invoked from a browser must support this category. CATEGORY_CAR_DOCK An activity to run when device is inserted into a car dock. CATEGORY_CAR_MODE Used to indicate that the activity can be used in a car environment. CATEGORY_DEFAULT Set if the activity should be an option for the default action (center press) to perform on a piece of data. CATEGORY_DESK_DOCK An activity to run when device is inserted into a car dock. CATEGORY_DEVELOPMENT_PREFERENCE This activity is a development preference panel. CATEGORY_EMBED Capable of running inside a parent activity container. CATEGORY_FRAMEWORK_INSTRUMENTATION_TEST To be used as code under test for framework instrumentation tests. CATEGORY_HE_DESK_DOCK An activity to run when device is inserted into a digital (high end) dock. CATEGORY_HOME This is the home activity, that is the first activity that is displayed when the device boots.

77 21 CATEGORY_INFO Provides information about the package it is in. 22 CATEGORY_LAUNCHER Should be displayed in the top-level launcher. 23 CATEGORY_LE_DESK_DOCK An activity to run when device is inserted into a analog (low end) dock. 24 CATEGORY_MONKEY This activity may be exercised by the monkey or other automated test tools. 25 CATEGORY_OPENABLE Used to indicate that a GET_CONTENT intent only wants URIs that can be opened with ContentResolver.openInputStream. 26 CATEGORY_PREFERENCE This activity is a preference panel. 27 CATEGORY_TAB Intended to be used as a tab inside of a containing TabActivity. 28 CATEGORY_TEST To be used as a test (not part of the normal user experience). 29 CATEGORY_UNIT_TEST To be used as a unit test (run through the Test Harness). You can check detail on Intent Filters in below section to understand how do we use categories to choose appropriate acivity coressponding to an Intent. EXTRAS This will be in key-value pairs for additional information that should be delivered to the component handling the intent. The extras can be set and read using the putextras() and getextras() methods respectively. Here is a list of Android Intent Standard Extra Data Android Intent standard Extra Data Following table lists down various important Android Intent Standard Extra Data. You can check Android Official Documentation for a complete list of Extra Data: S.N. 1 2 Extra Data & Description EXTRA_ALARM_COUNT Used as an int extra field in AlarmManager intents to tell the application being invoked how many pending alarms are being delievered with the intent. EXTRA_ALLOW_MULTIPLE Used to indicate that a ACTION_GET_CONTENT intent can allow the user to select and return multiple

78 items EXTRA_ALLOW_REPLACE Used as a boolean extra field with ACTION_INSTALL_PACKAGE to install a package. EXTRA_BCC A String[] holding addresses that should be blind carbon copied. EXTRA_CC A String[] holding addresses that should be carbon copied. EXTRA_CHANGED_COMPONENT_NAME_LIST This field is part of ACTION_PACKAGE_CHANGED, and contains a string array of all of the components that have changed. EXTRA_DATA_REMOVED Used as a boolean extra field in ACTION_PACKAGE_REMOVED intents to indicate whether this represents a full uninstall or a partial uninstall EXTRA_DOCK_STATE Used as an int extra field in ACTION_DOCK_EVENT intents to request the dock state. EXTRA_DOCK_STATE_CAR Used as an int value for EXTRA_DOCK_STATE to represent that the phone is in a car dock. EXTRA_DOCK_STATE_DESK Used as an int value for EXTRA_DOCK_STATE to represent that the phone is in a desk dock. EXTRA_ A String[] holding addresses that should be delivered to. EXTRA_HTML_TEXT A constant String that is associated with the Intent, used with ACTION_SEND to supply an alternative to EXTRA_TEXT as HTML formatted text. EXTRA_INTENT An Intent describing the choices you would like shown with ACTION_PICK_ACTIVITY. EXTRA_KEY_EVENT A KeyEvent object containing the event that triggered the creation of the Intent it is in. EXTRA_LOCAL_ONLY Used to indicate that a ACTION_GET_CONTENT intent should only return data that is on the local device. EXTRA_ORIGINATING_URI Used as a URI extra field with ACTION_INSTALL_PACKAGE and ACTION_VIEW to indicate the URI from which the local APK in the Intent data field originated from. EXTRA_PHONE_NUMBER A String holding the phone number originally entered in ACTION_NEW_OUTGOING_CALL, or the actual number to call in a ACTION_CALL EXTRA_SHORTCUT_ICON The name of the extra used to define the icon, as a Bitmap, of a shortcut. EXTRA_SHORTCUT_INTENT The name of the extra used to define the Intent of a shortcut.

79 20 EXTRA_SHORTCUT_NAME The name of the extra used to define the name of a shortcut. 21 EXTRA_STREAM URI holding a stream of data associated with the Intent, used with ACTION_SEND to supply the data being sent EXTRA_SUBJECT A constant string holding the desired subject line of a message. EXTRA_TEMPLATE The initial data to place in a newly created record. Use with ACTION_INSERT. 24 EXTRA_TEXT A constant CharSequence that is associated with the Intent, used with ACTION_SEND to supply the literal data to be sent. 25 EXTRA_TITLE A CharSequence dialog title to provide to the user when used with a ACTION_CHOOSER. 26 EXTRA_UID Used as an int extra field in ACTION_UID_REMOVED intents to supply the uid the package had been assigned. FLAGS These flags are optional part of Intent object and instruct the Android system how to launch an activity, and how to treat it after it's launched etc. COMPONENT NAME This optional field is an android ComponentName object representing either Activity, Service or BroadcastReceiver class. If it is set, the Intent object is delivered to an instance of the designated class otherwise Android uses other information in the Intent object to locate a suitable target. The component name is set by setcomponent(), setclass(), or setclassname() and read by getcomponent(). Types of Intents There are following two types of intents supported by Android till version 4.1 EXPLICIT INTENTS These intents designate the target component by its name and they are typically used for application-internal messages - such as an activity starting a subordinate service or launching a sister activity. For example: // Explicit Intent by specifying its class name Intent i = new Intent(this, TargetActivity.class); i.putextra("key1", "ABC"); i.putextra("key2", "123"); // Starts TargetActivity

80 startactivity(i); IMPLICIT INTENTS These intents do not name a target and the field for the component name is left blank. Implicit intents are often used to activate components in other applications. For example: // Implicit Intent by specifying a URI Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(" // Starts Implicit Activity startactivity(i); The target component which receives the intent can use the getextras() method to get the extra data sent by the source component. For example: // Get bundle object at appropriate place in your code Bundle extras = getintent().getextras(); // Extract data using passed keys String value1 = extras.getstring("key1"); String value2 = extras.getstring("key2"); Example Following example shows the functionality of a Android Intent to launch various Android built-in applications. Step Description 1 2 You will use Eclipse IDE to create an Android application and name it as IntentDemo under a package com.example.intentdemo. While creating this project, make sure you Target SDKand Compile With at the latest version of Android SDK to use higher levels of APIs. Modify src/mainactivity.java file and add the code to define two listeners corresponding two buttons ie. Start Browser and Start Phone. 3 Modify layout XML file res/layout/activity_main.xml to add three buttons in linear layout. 4 Modify res/values/strings.xml to define required constant values 5 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.intentdemo/mainactivity.java. package com.example.intentdemo; import android.net.uri; import android.os.bundle; import android.app.activity; import android.content.intent; import android.view.menu; import android.view.view; import android.widget.button; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) {

81 super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); Button startbrowser = (Button) findviewbyid(r.id.start_browser); startbrowser.setonclicklistener(new View.OnClickListener() { public void onclick(view view) { Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(" startactivity(i); ); Button startphone = (Button) findviewbyid(r.id.start_phone); startphone.setonclicklistener(new View.OnClickListener() { public void onclick(view view) { Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("tel: ")); startactivity(i); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action // bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/start_browser" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start_browser"/> <Button android:id="@+id/start_phone" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start_phone" /> </LinearLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">intentdemo</string> <string name="action_settings">settings</string> <string name="hello_world">hello world!</string> <string name="start_browser">start Browser</string> <string name="start_phone">start Phone</string>

82 </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.intentdemo" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" > <activity android:name="com.example.intentdemo.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Let's try to run your IntentDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: Now click on Start Browser button, which will start a browser configured and display as shown below:

83 Similar way you can launch phone interface using Start Phone button, which will allow you to dial already given phone number. Intent Filters You have seen how an Intent has been used to call an another activity. Android OS uses filters to pinpoint the set of Activities, Services, and Broadcast receivers that can handle the Intent with help of specified set of action, categories, data scheme associated with an Intent. You will use <intent-filter>element in the manifest file to list down actions, categories and data types associated with any activity, service, or broadcast receiver. Following is an example of a part of AndroidManifest.xml file to specify an activitycom.example.intentdemo.customactivity which can be invoked by either of the two mentioned actions, one category, and one data: <activity android:name=".customactivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.view" /> <action android:name="com.example.intentdemo.launch" /> <category android:name="android.intent.category.default" /> <data android:scheme="http" /> </intent-filter> </activity> Once this activity is defined along with above mentioned filters, other activities will be able to invoke this activity using either the android.intent.action.view, or using the com.example.intentdemo.launchaction provided their category is android.intent.category.default. The <data> element specifies the data type expected by the activity to be called and for above example our custom activity expects the data to start with the " There may be a situation that an intent can pass through the filters of more than one activity or service, the user may be asked which component to activate. An exception is raised if no target can be found.

84 There are following test Android checks before invoking an activity: A filter <intent-filter> may list more than one action as shown above but this list cannot be empty; a filter must contain at least one <action> element, otherwise it will block all intents. If more than one actions are mentioned then Android tries to match one of the mentioned actions before invoking the activity. A filter <intent-filter> may list zero, one or more than one categories. if there is no category mentioned then Android always pass this test but if more than one categories are mentioned then for an intent to pass the category test, every category in the Intent object must match a category in the filter. Each <data> element can specify a URI and a data type (MIME media type). There are separate attributes like scheme, host, port, and path for each part of the URI. An Intent object that contains both a URI and a data type passes the data type part of the test only if its type matches a type listed in the filter. Example Following example is a modification of the above example. Here we will see how Android resolves conflict if one intent is invoking two activities defined in, next how to invoke a custom activity using a filter and third one is an exception case if Android does not file appropriate activity defined for an intent. Step Description You will use Eclipse IDE to create an Android application and name it as IntentDemo under a package com.example.intentdemo. While creating this project, make sure you Target SDKand Compile With at the latest version of Android SDK to use higher levels of APIs. Modify src/mainactivity.java file and add the code to define three listeners corresponding to three buttons defined in layout file. Add a new src/customactivity.java file to have one custom activity which will be invoked by different intents. 4 Modify layout XML file res/layout/activity_main.xml to add three buttons in linear layout. 5 Add one layout XML file res/layout/custom_view.xml to add a simple <TextView> to show the passed data through intent. 6 Modify res/values/strings.xml to define required constant values 7 Modify AndroidManifest.xml to add <intent-filter> to define rules for your intent to invoke custom activity. 8 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.intentdemo/mainactivity.java. package com.example.intentdemo; import android.net.uri; import android.os.bundle; import android.app.activity; import android.content.intent; import android.view.menu; import android.view.view; import android.widget.button; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate);

85 setcontentview(r.layout.activity_main); // First intent to use ACTION_VIEW action with correct data Button startbrowser_a = (Button) findviewbyid(r.id.start_browser_a); startbrowser_a.setonclicklistener(new View.OnClickListener() { public void onclick(view view) { Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(" startactivity(i); ); // Second intent to use LAUNCH action with correct data Button startbrowser_b = (Button) findviewbyid(r.id.start_browser_b); startbrowser_b.setonclicklistener(new View.OnClickListener() { public void onclick(view view) { Intent i = new Intent("com.example.intentdemo.LAUNCH", Uri.parse(" startactivity(i); ); // Third intent to use LAUNCH action with incorrect data Button startbrowser_c = (Button) findviewbyid(r.id.start_browser_c); startbrowser_c.setonclicklistener(new View.OnClickListener() { public void onclick(view view) { Intent i = new Intent("com.example.intentdemo.LAUNCH", Uri.parse(" startactivity(i); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the // action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; Following is the content of the modified main activity filesrc/com.example.intentdemo/customactivity.java. package com.example.intentdemo; import android.app.activity; import android.net.uri; import android.os.bundle; import android.widget.textview; public class CustomActivity extends Activity public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.custom_view); TextView label = (TextView) findviewbyid(r.id.show_data);

86 Uri url = getintent().getdata(); label.settext(url.tostring()); Following will be the content of res/layout/activity_main.xml file: <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/start_browser_a" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start_browser_a"/> <Button android:id="@+id/start_browser_b" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start_browser_b"/> <Button android:id="@+id/start_browser_c" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start_browser_c"/> </LinearLayout> Following will be the content of res/layout/custom_view.xml file: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/show_data" android:layout_width="fill_parent" android:layout_height="400dp"/> </LinearLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">intentdemo</string> <string name="action_settings">settings</string> <string name="hello_world">hello world!</string> <string name="start_browser_a">start Browser with VIEW action</string> <string name="start_browser_b">start Browser with LAUNCH action</string> <string name="start_browser_c">exception Condition</string> </resources> Following is the default content of AndroidManifest.xml:

87 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.intentdemo" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" > <activity android:name="com.example.intentdemo.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <activity android:name="com.example.intentdemo.customactivity" <intent-filter> <action android:name="android.intent.action.view" /> <action android:name="com.example.intentdemo.launch" /> <category android:name="android.intent.category.default" /> <data android:scheme="http" /> </intent-filter> </activity> </application> </manifest> Let's try to run your IntentDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

88 Now let's start with first button "Start Browser with VIEW Action". Here we have defined our custom activity with a filter "android.intent.action.view", and there is already one default activity against VIEW action defined by Android which is launching web browser, So android displays following two options to select the activity you want to launch.

89 Now if you select Browser, then Android will launch web browser and open example.com website but if you select IndentDemo option then Android will launch CustomActivity which does nothing but just capture passed data and displays in a text view as follows:

90 Now go back using back button and click on "Start Browser with LAUNCH Action" button, here Android applies filter to choose define activity and it simply launch your custom activity and again it displays following screen: Again, go back using back button and click on "Exception Condition" button, here Android tries to find out a valid filter for the given intent but it does not find a valid activity defined because this time we have used data as https instead of http though we are giving a correct action, so Android raises an exception and shows following screen:

91 CHAPTER 13 UI Layouts The basic building block for user interface is a View object which is created from the View class and 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 like buttons, text fields, etc. The ViewGroup is a subclass of View and provides invisible container that hold other Views or other ViewGroups and define their layout properties. At third level we have different layouts which are subclasses of ViewGroup class and a typical layout defines the visual structure for an Android user interface and can be created either at run time usingview/viewgroup objects or you can declare your layout using simple XML file main_layout.xml which is located in the res/layout folder of your project. This tutorial is more about creating your GUI based on layouts defined in XML file. A layout may contain any type of widgets such as buttons, labels, textboxes, and so on. Following is a simple example of XML file having LinearLayout: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="this is a TextView" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="this is a Button" /> </LinearLayout> <!-- More GUI components go here --> Once your layout is defined, you can load the layout resource from your application code, in youractivity.oncreate() callback implementation as shown below: public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main);

92 Android Layout Types There are number of Layouts provided by Android which you will use in almost all the Android applications to provide different view, look and feel. S.N. Layout & Description Linear Layout LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally. Relative Layout RelativeLayout is a view group that displays child views in relative positions. Table Layout TableLayout is a view that groups views into rows and columns. Absolute Layout AbsoluteLayout enables you to specify the exact location of its children. Frame Layout The FrameLayout is a placeholder on screen that you can use to display a single view. List View ListView is a view group that displays a list of scrollable items. Grid View GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. Linear Layout Android LinearLayout is a view group that aligns all children in a single direction, vertically orhorizontally. LinearLayout Attributes Following are the important attributes specific to LinearLayout: Attribute android:id android:baselinealigned android:divider android:gravity android:orientation Description This is the ID which uniquely identifies the layout. This must be a boolean value, either "true" or "false" and prevents the layout from aligning its children's baselines. This is drawable to use as a vertical divider between buttons. You use a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb". This specifies how an object should position its content, on both the X and Y axes. Possible values are top, bottom, left, right, center, center_vertical, center_horizontal etc. This specifies the direction of arrangmet and you will use "horizontal" for a row, "vertical" for a column. The default is horizontal. Example This example will take you through simple steps to show how to create your own Android application using Linear Layout. Follow the following steps to modify the Android application we created in Hello World Example chapter: Step Description

93 1 You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. 2 Modify the detault content of res/layout/activity_main.xml file to include few buttons in linear layout. 3 Define required constants start_service, pause_service and stop_service inres/values/strings.xml file 4 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.helloworld/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.helloworld; import android.os.bundle; import android.app.activity; import android.view.menu; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/btnstartservice" android:layout_width="150px" android:layout_height="wrap_content" android:text="@string/start_service" <Button android:id="@+id/btnpauseservice" android:layout_width="150px" android:layout_height="wrap_content" android:text="@string/pause_service" <Button android:id="@+id/btnstopservice" android:layout_width="150px" android:layout_height="wrap_content" android:text="@string/stop_service" </LinearLayout> Following will be the content of res/values/strings.xml to define two new constants:

94 <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">helloworld</string> <string name="action_settings">settings</string> <string name="start_service">start</string> <string name="pause_service">pause</string> <string name="stop_service">stop</string> </resources> Let's try to run our modified Hello World! application we just modified. I assume you had created youravd while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: Now let's change the orientation of Layout as android:orientation="horizontal" and try to run the same application, it will give following screen:

95 Relative Layout Android RelativeLayout enables you to specify how child views are positioned relative to each other. The position of each view can be specified as relative to sibling elements or relative to the parent. RelativeLayout Attributes Following are the important attributes specific to RelativeLayout: Attribute android:id android:gravity android:ignoregravity Description This is the ID which uniquely identifies the layout. This specifies how an object should position its content, on both the X and Y axes. Possible values are top, bottom, left, right, center, center_vertical, center_horizontal etc. This indicates what view should not be affected by gravity. Using RelativeLayout, you can align two elements by right border, or make one below another, centered in the screen, centered left, and so on. By default, all child views are drawn at the top-left of the layout, so you must define the position of each view using the various layout properties available fromrelativelayout.layoutparams and few of the important attributes are given below: Attribute android:layout_above android:layout_alignbottom android:layout_alignleft Description Positions the bottom edge of this view above the given anchor view ID and must be a reference to another resource, in the form "@[+][package:]type:name" Makes the bottom edge of this view match the bottom edge of the given anchor view ID and must be a reference to another resource, in the form "@[+][package:]type:name". Makes the left edge of this view match the left edge of the given anchor view ID and must be a reference to another resource, in the form

96 android:layout_alignparentbottom android:layout_alignparentend android:layout_alignparentleft android:layout_alignparentright android:layout_alignparentstart android:layout_alignparenttop android:layout_alignright android:layout_alignstart android:layout_aligntop android:layout_below android:layout_centerhorizontal android:layout_centerinparent android:layout_centervertical android:layout_toendof android:layout_toleftof android:layout_torightof android:layout_tostartof If true, makes the bottom edge of this view match the bottom edge of the parent. Must be a boolean value, either "true" or "false". If true, makes the end edge of this view match the end edge of the parent. Must be a boolean value, either "true" or "false". If true, makes the left edge of this view match the left edge of the parent. Must be a boolean value, either "true" or "false". If true, makes the right edge of this view match the right edge of the parent. Must be a boolean value, either "true" or "false". If true, makes the start edge of this view match the start edge of the parent. Must be a boolean value, either "true" or "false". If true, makes the top edge of this view match the top edge of the parent. Must be a boolean value, either "true" or "false". Makes the right edge of this view match the right edge of the given anchor view ID and must be a reference to another resource, in the form "@[+][package:]type:name". Makes the start edge of this view match the start edge of the given anchor view ID and must be a reference to another resource, in the form "@[+][package:]type:name". Makes the top edge of this view match the top edge of the given anchor view ID and must be a reference to another resource, in the form "@[+][package:]type:name". Positions the top edge of this view below the given anchor view ID and must be a reference to another resource, in the form "@[+][package:]type:name". If true, centers this child horizontally within its parent. Must be a boolean value, either "true" or "false". If true, centers this child horizontally and vertically within its parent. Must be a boolean value, either "true" or "false". If true, centers this child vertically within its parent. Must be a boolean value, either "true" or "false". Positions the start edge of this view to the end of the given anchor view ID and must be a reference to another resource, in the form "@[+][package:]type:name". Positions the right edge of this view to the left of the given anchor view ID and must be a reference to another resource, in the form "@[+][package:]type:name". Positions the left edge of this view to the right of the given anchor view ID and must be a reference to another resource, in the form "@[+][package:]type:name". Positions the end edge of this view to the start of the given anchor view ID and must be a reference to another resource, in the form "@[+][package:]type:name".

97 Example This example will take you through simple steps to show how to create your own Android application using Relative Layout. Follow the following steps to modify the Android application we created in Hello World Example chapter: Step Description 1 You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. 2 Modify the detault content of res/layout/activity_main.xml file to include few widgets in Relative layout. 3 Define required constants in res/values/strings.xml file 4 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.helloworld/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.helloworld; import java.text.simpledateformat; import java.util.calendar; import java.util.date; import android.os.bundle; import android.app.activity; import android.text.format.dateformat; import android.view.menu; import android.widget.textview; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd"); Date date = new Date(); String nowdate = dateformat.format(date); TextView dateview = (TextView)findViewById(R.id.dates);

98 dateview.settext(nowdate); SimpleDateFormat timeformat = new SimpleDateFormat("HH:mm:ss"); String nowtime = timeformat.format(date); TextView timeview = (TextView)findViewById(R.id.times); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <RelativeLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingleft="16dp" android:paddingright="16dp" > <EditText android:id="@+id/name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/reminder" /> <TextView android:id="@+id/dates" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_below="@id/name" android:layout_alignparentleft="true"

99 /> <TextView android:layout_width="96dp" android:layout_height="wrap_content" android:layout_alignparentright="true" /> <Button android:layout_width="96dp" android:layout_height="wrap_content" android:layout_centerinparent="true" /> </RelativeLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">helloworld</string> <string name="action_settings">settings</string> <string name="reminder">enter your name</string> <string name="done">done</string> </resources> Let's try to run our modified Hello World! application we just modified. I assume you had created youravd while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

100 Table Layout Android TableLayout groups views into rows and columns. You will use the <TableRow> element to build a row in the table. Each row has zero or more cells; each cell can hold one View object. TableLayout containers do not display border lines for their rows, columns, or cells. TableLayout Attributes Following are the important attributes specific to TableLayout: Attribute android:id android:collapsecolumns android:collapsecolumns android:stretchcolumns Description This is the ID which uniquely identifies the layout. This specifies the zero-based index of the columns to collapse. The column indices must be separated by a comma: 1, 2, 5. The zero-based index of the columns to shrink. The column indices must be separated by a comma: 1, 2, 5. The zero-based index of the columns to stretch. The column indices must be separated by a comma: 1, 2, 5. Example This example will take you through simple steps to show how to create your own Android application using Table Layout. Follow the following steps to modify the Android application we created in Hello World Example chapter: Step Description 1 You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter.

101 2 Modify the detault content of res/layout/activity_main.xml file to include few widgets in table layout. 3 Define required constants in res/values/strings.xml file 4 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.helloworld/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.helloworld; import android.os.bundle; import android.app.activity; import android.view.menu; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <TableLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent"> <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> <TableRow> <TextView android:text="last Name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" />

102 <EditText android:width="100px" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </TableRow> </TableLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">helloworld</string> <string name="action_settings">settings</string> </resources> Let's try to run our modified Hello World! application we just modified. I assume you had created youravd while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: Absolute Layout An Absolute Layout lets you specify exact locations (x/y coordinates) of its children. Absolute layouts are less flexible and harder to maintain than other types of layouts without absolute positioning. AbsoluteLayout Attributes Following are the important attributes specific to AbsoluteLayout: Attribute android:id Description This is the ID which uniquely identifies the layout.

103 android:layout_x android:layout_y This specifies the x-coordinate of the view. This specifies the y-coordinate of the view. Example This example will take you through simple steps to show how to create your own Android application using absolute layout. Follow the following steps to modify the Android application we created in Hello World Example chapter: Step Description 1 You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. 2 Modify the detault content of res/layout/activity_main.xml file to include few widgets in absolute layout. 3 Define required constants in res/values/strings.xml file 4 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.helloworld/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.helloworld; import android.os.bundle; import android.app.activity; import android.view.menu; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <AbsoluteLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:layout_width="100dp" android:layout_height="wrap_content" android:text="ok" android:layout_x="50px" android:layout_y="361px" /> <Button android:layout_width="100dp"

104 android:layout_height="wrap_content" android:text="cancel" android:layout_x="225px" android:layout_y="361px" /> </AbsoluteLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">helloworld</string> <string name="action_settings">settings</string> </resources> Let's try to run our modified Hello World! application we just modified. I assume you had created youravd while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: Frame Layout Frame Layout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute. FrameLayout Attributes

105 Following are the important attributes specific to FrameLayout: Attribute android:id android:foreground android:foregroundgravity android:measureallchildren Description This is the ID which uniquely identifies the layout. This defines the drawable to draw over the content and possible values may be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb". Defines the gravity to apply to the foreground drawable. The gravity defaults to fill. Possible values are top, bottom, left, right, center, center_vertical, center_horizontal etc. Determines whether to measure all children or just those in the VISIBLE or INVISIBLE state when measuring. Defaults to false. Example This example will take you through simple steps to show how to create your own Android application using frame layout. Follow the following steps to modify the Android application we created in Hello World Example chapter: Step Description 1 You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. 2 Modify the detault content of res/layout/activity_main.xml file to include few widgets in frame layout. 3 Define required constants in res/values/strings.xml file 4 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.helloworld/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.helloworld; import android.os.bundle; import android.app.activity; import android.view.menu; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <FrameLayout xmlns:android=" android:layout_width="fill_parent"

106 android:layout_height="fill_parent"> <ImageView android:scaletype="fitcenter" android:layout_height="250px" android:layout_width="250px"/> <TextView android:text="frame Demo" android:textsize="30px" android:textstyle="bold" android:layout_height="fill_parent" android:layout_width="fill_parent" android:gravity="center"/> </FrameLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">helloworld</string> <string name="action_settings">settings</string> </resources> Let's try to run our modified Hello World! application we just modified. I assume you had created youravd while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: List View

107 Android ListView is a view which groups several items and display them in vertical scrollable list. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database. An adapter actually bridges between UI components and the data source that fill data into UI Component. Adapter can be used to supply the data to like spinner, list view, grid view etc. The ListView and GridView are subclasses of AdapterView and they can be populated by binding them to an Adapter, which retrieves data from an external source and creates a View that represents each data entry. Android provides several subclasses of Adapter that are useful for retrieving different kinds of data and building views for an AdapterView ( ie. ListView or GridView). The two most common adapters arearrayadapter and SimpleCursorAdapter. We will see separate examples for both the adapters. ListView Attributes Following are the important attributes specific to GridView: Attribute android:id Description This is the ID which uniquely identifies the layout. android:divider This is drawable or color to draw between list items.. android:dividerheight android:entries android:footerdividersenabled android:headerdividersenabled This specifies height of the divider. This could be in px, dp, sp, in, or mm. Specifies the reference to an array resource that will populate the ListView. When set to false, the ListView will not draw the divider before each footer view. The default value is true. When set to false, the ListView will not draw the divider after each header view. The default value is true. ArrayAdapter You can use this adapter when your data source is an array. By default, ArrayAdapter creates a view for each array item by calling tostring() on each item and placing the contents in a TextView. Consider you have an array of strings you want to display in a ListView, initialize a new ArrayAdapter using a constructor to specify the layout for each string and the string array: ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.ListView, StringArray); Here are arguments for this constructor: First argument this is the application context. Most of the case, keep it this. Second argument will be layout defined in XML file and having TextView for each string in the array. Final argument is an array of strings which will be populated in the text view. Once you have array adaptor created, then simply call setadapter() on your ListView object as follows: ListView listview = (ListView) findviewbyid(r.id.listview); listview.setadapter(adapter); You will define your list view under res/layout directory in an XML file. For our example we are going to using activity_main.xml file.

108 EXAMPLE Following is the example which will take you through simple steps to show how to create your own Android application using ListView. Follow the following steps to modify the Android application we created in Hello World Example chapter: Step Description 1 2 You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. Modify the detault content of res/layout/activity_main.xml file to include ListView content with the self explanatory attributes. 3 Define required constants in res/values/strings.xml file. 4 Create a Text View file res/layout/activity_listview.xml. This file will have setting to display all the list items. So you can customize its fonts, padding, color etc. using this file. 6 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.helloworld/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.helloworld; import android.os.bundle; import android.app.activity; import android.view.menu; import android.widget.arrayadapter; import android.widget.listview; public class MainActivity extends Activity { // Array of strings... String[] countryarray = {"India", "Pakistan", "USA", protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, countryarray); ListView listview = (ListView) findviewbyid(r.id.country_list); listview.setadapter(adapter); Following will be the content of res/layout/activity_main.xml file: <LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".listactivity" > <ListView

109 android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> </LinearLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">helloworld</string> <string name="action_settings">settings</string> </resources> Following will be the content of res/layout/activity_listview.xml file: <?xml version="1.0" encoding="utf-8"?> <!-- Single List Item Design --> <TextView xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dip" android:textsize="16dip" android:textstyle="bold" > </TextView> Let's try to run our modified Hello World! application we just modified. I assume you had created youravd while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

110 SimpleCursorAdapter You can use this adapter when your data source is a database Cursor. When usingsimplecursoradapter, you must specify a layout to use for each row in the Cursor and which columns in the Cursor should be inserted into which views of the layout. For example, if you want to create a list of people's names and phone numbers, you can perform a query that returns a Cursor containing a row for each person and columns for the names and numbers. You then create a string array specifying which columns from the Cursor you want in the layout for each result and an integer array specifying the corresponding views that each column should be placed: String[] fromcolumns = {ContactsContract.Data.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER; int[] toviews = {R.id.display_name, R.id.phone_number; When you instantiate the SimpleCursorAdapter, pass the layout to use for each result, the Cursor containing the results, and these two arrays: SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.person_name_and_number, cursor, fromcolumns, toviews, 0); ListView listview = getlistview(); listview.setadapter(adapter); The SimpleCursorAdapter then creates a view for each row in the Cursor using the provided layout by inserting each fromcolumns item into the corresponding toviews view. GridView Android GridView shows items in two-dimensional scrolling grid (rows & columns) and the grid items are not necessarily predetermined but they automatically inserted to the layout using a ListAdapter An adapter actually bridges between UI components and the data source that fill data into UI Component. Adapter can be used to supply the data to like spinner, list view, grid view etc. The ListView and GridView are subclasses of AdapterView and they can be populated by binding them to an Adapter, which retrieves data from an external source and creates a View that represents each data entry. GridView Attributes Following are the important attributes specific to GridView: Attribute android:id android:columnwidth android:gravity android:horizontalspacing android:numcolumns Description This is the ID which uniquely identifies the layout. This specifies the fixed width for each column. This could be in px, dp, sp, in, or mm. Specifies the gravity within each cell. Possible values are top, bottom, left, right, center, center_vertical, center_horizontal etc. Defines the default horizontal spacing between columns. This could be in px, dp, sp, in, or mm. Defines how many columns to show. May be an integer value, such as "100" or auto_fit which means display as many columns as possible to fill the available space.

111 Defines how columns should stretch to fill the available empty space, if any. This must be either of the values: none: Stretching is disabled. android:stretchmode spacingwidth: The spacing between each column is stretched. columnwidth: Each column is stretched equally. spacingwidthuniform: The spacing between each column is uniformly stretched.. android:verticalspacing Defines the default vertical spacing between rows. This could be in px, dp, sp, in, or mm. Example This example will take you through simple steps to show how to create your own Android application using GridView. Follow the following steps to modify the Android application we created in Hello World Example chapter: Step Description 1 2 You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. Modify the detault content of res/layout/activity_main.xml file to include GridView content with the self explanatory attributes. 3 Define required constants in res/values/strings.xml file. 4 5 Let's put few pictures in res/drawable-hdpi folder. I have put sample0.jpg, sample1.jpg, sample2.jpg, sample3.jpg, sample4.jpg, sample5.jpg, sample6.jpg and sample7.jpg. Create a new class called ImageAdapter under a package com.example.helloworld that extends BaseAdapter. This class will implement functionality of an adaptor to be used to fill the view. 6 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.helloworld/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.helloworld; import android.os.bundle; import android.app.activity; import android.view.menu; import android.widget.gridview; public class MainActivity extends Activity

112 protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); GridView gridview = (GridView) findviewbyid(r.id.gridview); gridview.setadapter(new public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android=" android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnwidth="90dp" android:numcolumns="auto_fit" android:verticalspacing="10dp" android:horizontalspacing="10dp" android:stretchmode="columnwidth" android:gravity="center" /> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources>

113 <string name="app_name">helloworld</string> <string name="action_settings">settings</string> </resources> Following will be the content of src/com.example.helloworld/imageadapter.java file: package com.example.helloworld; import android.content.context; import android.view.view; import android.view.viewgroup; import android.widget.baseadapter; import android.widget.gridview; import android.widget.imageview; public class ImageAdapter extends BaseAdapter { private Context mcontext; // Constructor public ImageAdapter(Context c) { mcontext = c; public int getcount() { return mthumbids.length; public Object getitem(int position) { return null; public long getitemid(int position) { return 0;

114 // create a new ImageView for each item referenced by the Adapter public View getview(int position, View convertview, ViewGroup parent) { ImageView imageview; if (convertview == null) { imageview = new ImageView(mContext); imageview.setlayoutparams(new GridView.LayoutParams(85, 85)); imageview.setscaletype(imageview.scaletype.center_crop); imageview.setpadding(8, 8, 8, 8); else { imageview = (ImageView) convertview; imageview.setimageresource(mthumbids[position]); return imageview; // Keep all Images in array public Integer[] mthumbids = { R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7, R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7, R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7 ;

115 Let's try to run our modified Hello World! application we just modified. I assume you had created youravd while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: Sub-Activity Example Let's extend the functionality of above example where we will show selected grid image in full screen. To achieve this we need to introduce a new activity. Just keep in mind for any activity we need perform all the steps like we have to implement an activity class, define that activity in AndroidManifest.xml file, define related layout and finally link that sub-activity with the main activity by it in the main activity class. So let's follow the steps to modify above example:

116 Step Description 1 2 You will use Eclipse IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. Create a new Activity class as SingleViewActivity.java under a packagecom.example.helloworld as shown below. 3 Create new layout file for the new activity under res/layout/ folder. Let's name this XML file as single_view.xml. 4 Define your new activity in AndroidManifest.xml file using tag. An application can have one or more activities without any restrictions. 5 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.helloworld/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.helloworld; import android.app.activity; import android.content.intent; import android.os.bundle; import android.view.menu; import android.view.view; import android.widget.adapterview; import android.widget.adapterview.onitemclicklistener; import android.widget.gridview; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); GridView gridview = (GridView) findviewbyid(r.id.gridview); gridview.setadapter(new ImageAdapter(this)); gridview.setonitemclicklistener(new OnItemClickListener() { public void onitemclick(adapterview<?> parent, View v,

117 int position, long id) { // Send intent to SingleViewActivity Intent i = new Intent(getApplicationContext(), SingleViewActivity.class); // Pass image index i.putextra("id", position); startactivity(i); public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of new activity file src/com.example.helloworld/singleviewactivity.javafile: package com.example.helloworld; import android.app.activity; import android.content.intent; import android.os.bundle; import android.widget.imageview; public class SingleViewActivity extends Activity public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.single_view);

118 // Get intent data Intent i = getintent(); // Selected image id int position = i.getextras().getint("id"); ImageAdapter imageadapter = new ImageAdapter(this); ImageView imageview = (ImageView) findviewbyid(r.id.singleview); imageview.setimageresource(imageadapter.mthumbids[position]); Following will be the content of res/layout/single_view.xml file: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/singleview" android:layout_width="fill_parent" android:layout_height="fill_parent"/> </LinearLayout> Following will be the content of AndroidManifest.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.helloworld" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8"

119 android:targetsdkversion="17" /> <application android:allowbackup="true" > <activity android:name="com.example.helloworld.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <activity android:name=".singleviewactivity"></activity> </application> </manifest> Let's try to run our modified Hello World! application we just modified. I assume you had created youravd while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

120 Now if you click on either of the images it will be displayed as a single image, for example:

121 Kindly note above mentioned images have been taken from Android official website. Layout Attributes Each layout has a set of attributes which define the visual properties of that layout. There are few common attributes among all the layouts and their are other attributes which are specific to that layout. Following are common attributes and will be applied to all the layouts: Attribute android:id Description This is the ID which uniquely identifies the view.

122 android:layout_width android:layout_height android:layout_margintop android:layout_marginbottom android:layout_marginleft android:layout_marginright android:layout_gravity android:layout_weight android:layout_x android:layout_y android:layout_width android:layout_width android:paddingleft android:paddingright android:paddingtop android:paddingbottom This is the width of the layout. This is the height of the layout This is the extra space on the top side of the layout. This is the extra space on the bottom side of the layout. This is the extra space on the left side of the layout. This is the extra space on the right side of the layout. This specifies how child Views are positioned. This specifies how much of the extra space in the layout should be allocated to the View. This specifies the x-coordinate of the layout. This specifies the y-coordinate of the layout. This is the width of the layout. This is the width of the layout. This is the left padding filled for the layout. This is the right padding filled for the layout. This is the top padding filled for the layout. This is the bottom padding filled for the layout. Here width and height are the dimension of the layout/view which can be specified in terms of dp (Densityindependent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of an inch), px( Pixels), mm ( Millimeters) and finally in (inches). You can specify width and height with exact measurements but more often, you will use one of these constants to set the width or height: android:layout_width=wrap_content tells your view to size itself to the dimensions required by its content. android:layout_width=fill_parent tells your view to become as big as its parent view. Gravity attribute plays important role in positioning the view object and it can take one or more (separated by ' ') of the following constant values. Constant Value Description top 0x30 Push object to the top of its container, not changing its size. bottom 0x50 Push object to the bottom of its container, not changing its size. left 0x03 Push object to the left of its container, not changing its size. right 0x05 Push object to the right of its container, not changing its size. center_vertical 0x10 Place object in the vertical center of its container, not changing its size. fill_vertical 0x70 Grow the vertical size of the object if needed so it completely fills its container. center_horizontal 0x01 Place object in the horizontal center of its container, not changing its size.

123 fill_horizontal 0x07 Grow the horizontal size of the object if needed so it completely fills its container. center fill clip_vertical clip_horizontal 0x11 0x77 0x80 0x08 Place the object in the center of its container in both the vertical and horizontal axis, not changing its size. Grow the horizontal and vertical size of the object if needed so it completely fills its container. Additional option that can be set to have the top and/or bottom edges of the child clipped to its container's bounds. The clip will be based on the vertical gravity: a top gravity will clip the bottom edge, a bottom gravity will clip the top edge, and neither will clip both edges. Additional option that can be set to have the left and/or right edges of the child clipped to its container's bounds. The clip will be based on the horizontal gravity: a left gravity will clip the right edge, a right gravity will clip the left edge, and neither will clip both edges. start 0x Push object to the beginning of its container, not changing its size. end View Identification 0x Push object to the end of its container, not changing its size. A view object may have a unique ID assigned to it which will identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is: android:id="@+id/my_button" Following is a brief description and + signs: The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must be created and added to our resources. To create an instance of the view object and capture it from the layout, use the following: Button mybutton = (Button) findviewbyid(r.id.my_button);

124 CHAPTER 14 UI Controls An Android application user interface is everything that the user can see and interact with. You have learned about the various layouts that you can use to position your views in an activity. This chapter will give you detail on various views. A View is an object that draws something on the screen that the user can interact with and aviewgroup is an object that holds other View (and ViewGroup) objects in order to define the layout of the user interface. You define your layout in an XML file which offers a human-readable structure for the layout, similar to HTML. For example, a simple vertical layout with a text view and a button looks like this: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="i am a TextView" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="i am a Button" /> </LinearLayout> Android UI Controls There are number of UI controls provided by Android that allow you to build the graphical user interface for your app. S.N. UI Control & Description TextView This control is used to display text to the user. EditText EditText is a predefined subclass of TextView that includes rich editing capabilities. AutoCompleteTextView The AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of completion

125 suggestions automatically while the user is typing Button A push-button that can be pressed, or clicked, by the user to perform an action. ImageButton AbsoluteLayout enables you to specify the exact location of its children. CheckBox An on/off switch that can be toggled by the user. You should use checkboxes when presenting users with a group of selectable options that are not mutually exclusive. ToggleButton An on/off button with a light indicator. RadioButton The RadioButton has two states: either checked or unchecked. RadioGroup A RadioGroup is used to group together one or more RadioButtons. ProgressBar The ProgressBar view provides visual feedback about some ongoing tasks, such as when you are performing a task in the background. Spinner A drop-down list that allows users to select one value from a set. TimePicker The TimePicker view enables users to select a time of the day, in either 24-hour mode or AM/PM mode. 13 DatePicker The DatePicker view enables users to select a date of the day. TextView A TextView displays text to the user and optionally allows them to edit it. A TextView is a complete text editor, however the basic class is configured to not allow editing. TextView Attributes Following are the important attributes related to TextView control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time. Attribute android:id Description This is the ID which uniquely identifies the control. If set, specifies that this TextView has a textual input method and should automatically capitalize what the user types. android:capitalize Don't automatically capitalize anything - 0 Capitalize the first word of each sentence - 1 Capitalize the first letter of every word - 2

126 Capitalize every character - 3 android:cursorvisible android:editable android:fontfamily android:gravity android:hint android:inputtype android:maxheight android:maxwidth android:minheight android:minwidth android:password android:phonenumber android:text android:textallcaps android:textcolor android:textcolorhighlight android:textcolorhint android:textisselectable android:textsize Makes the cursor visible (the default) or invisible. Default is false. If set to true, specifies that this TextView has an input method. Font family (named by string) for the text. Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than the view. Hint text to display when the text is empty. The type of data being placed in a text field. Phone, Date, Time, Number, Password etc. Makes the TextView be at most this many pixels tall. Makes the TextView be at most this many pixels wide. Makes the TextView be at least this many pixels tall. Makes the TextView be at least this many pixels wide. Whether the characters of the field are displayed as password dots instead of themselves. Possible value either "true" or "false". If set, specifies that this TextView has a phone number input method. Possible value either "true" or "false". Text to display. Present the text in ALL CAPS. Possible value either "true" or "false". Text color. May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb". Color of the text selection highlight. Color of the hint text. May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb". Indicates that the content of a non-editable text can be selected. Possible value either "true" or "false". Size of the text. Recommended dimension type for text is "sp" for scaled-pixels (example: 15sp). Style (bold, italic, bolditalic) for the text. You can use or more of the following values separated by ' '. android:textstyle normal - 0 bold - 1 italic - 2 android:typeface Typeface (normal, sans, serif, monospace) for the text. You can use or more of the following values separated by ' '.

127 normal - 0 sans - 1 serif - 2 monospace 3 Example This example will take you through simple steps to show how to create your own Android application using Linear Layout and TextView. Step Description 1 You will use Eclipse IDE to create an Android application and name it as GUIDemo under a package com.example.guidemo as explained in the Hello World Example chapter. 2 Modify src/mainactivity.java file to add a click event. 2 Modify the detault content of res/layout/activity_main.xml file to include Android UI control. 3 Define required constants in res/values/strings.xml file 4 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity file src/com.example.guidemo/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.guidemo; import android.os.bundle; import android.app.activity; import android.view.menu; import android.view.view; import android.widget.textview; import android.widget.toast; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); //--- text view--- TextView txtview = (TextView) findviewbyid(r.id.text_id); final String Label = txtview.gettext().tostring(); txtview.setonclicklistener(new View.OnClickListener() { public void onclick(view v) { Toast.makeText(getApplicationContext(), "You have clicked the Label : " + Label, Toast.LENGTH_LONG).show(); );

128 @Override public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity" > <TextView android:id="@+id/text_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:capitalize="characters" android:text="@string/hello_world" /> </RelativeLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">guidemo</string> <string name="action_settings">settings</string> <string name="hello_world">hello world!</string> </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity

129 android:name="com.example.guidemo.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Let's try to run your GUIDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: Now let's click on the Lable "Hello World", it will give following screen:

130 Exercise: I will recommend to try above example with different attributes of TextView in Layout XML file as well at programming time to have different look and feel of the TextView. Try to make it editable, change to font color, font family, width, textsize etc and see the result. You can also try above example with multiple TextView controls in one acitivity. EditText A EditText is an overlay over TextView that configures itself to be editable. It is the predefined subclass of TextView that includes rich editing capabilities. EditText Attributes Following are the important attributes related to EditText control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time. Inherited from android.widget.textview Class: Attribute android:autotext android:drawablebottom android:drawableright android:editable android:text Description If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors. This is the drawable to be drawn below the text. This is the drawable to be drawn to the right of the text. If set, specifies that this TextView has an input method. This is the Text to display.

131 Inherited from android.view.view Class: Attribute android:background android:contentdescription android:id android:onclick android:visibility Description This is a drawable to use as the background. This defines text that briefly describes content of the view. This supplies an identifier name for this view, This is the name of the method in this View's context to invoke when the view is clicked. This controls the initial visibility of the view. Example This example will take you through simple steps to show how to create your own Android application using Linear Layout and EditText. Step Description 1 You will use Eclipse IDE to create an Android application and name it as GUIDemo2 under a package com.example.guidemo2 as explained in the Hello World Example chapter. 2 Modify src/mainactivity.java file to add a click event. 2 Modify the detault content of res/layout/activity_main.xml file to include Android UI control. 3 Define required constants in res/values/strings.xml file 4 Run the application to launch Android emulator and verify the result of the changes done in the application. Following is the content of the modified main activity filesrc/com.example.guidemo2/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.guidemo2; import android.os.bundle; import android.app.activity; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; import android.widget.toast; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); final EditText etext; final Button btn; etext = (EditText) findviewbyid(r.id.edittext); btn = (Button) findviewbyid(r.id.button); btn.setonclicklistener(new OnClickListener() {

132 public void onclick(view v) { String str = etext.gettext().tostring(); Toast msg = Toast.makeText(getBaseContext(),str, Toast.LENGTH_LONG); msg.show(); msg.show(); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity" > <TextView android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentleft="true" android:layout_alignparenttop="true" android:layout_marginleft="14dp" android:layout_margintop="18dp" android:text="@string/example_edittext" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/textview1" android:layout_below="@+id/textview1" android:layout_margintop="130dp" android:text="@string/show_the_text" /> <EditText android:id="@+id/edittext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignleft="@+id/button" android:layout_below="@+id/textview1" android:layout_margintop="61dp" android:ems="10" android:text="@string/enter_text" android:inputtype="text" />

133 </RelativeLayout> Following will be the content of res/values/strings.xml to define these new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">guidemo1</string> <string name="action_settings">settings</string> <string name="example_edittext">example showing EditText</string> <string name="show_the_text">show the Text</string> <string name="enter_text">text changes</string> </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo2" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" > <activity android:name="com.example.guidemo2.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Let's try to run your GUIDemo2 application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

134 Now let's click on the Button "Show the Text", it will give following screen: Now let's change the text to "tutorialspoint website". Click on the Button "Show the Text", it will give following screen:

135 Exercise: I will recommend to try above example with different attributes of EditText in Layout XML file as well at programming time to have different look and feel of the EditText. Try to make it editable, change to font color, font family, width, textsize etc and see the result. You can also try above example with multiple EditText controls in one activity. AutoCompleteTextView A AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of completion suggestions automatically while the user is typing. The list of suggestions is displayed in drop down menu. The user can choose an item from there to replace the content of edit box with. AutoCompleteTextView Attributes Following are the important attributes related to AutoCompleteTextView control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time. Attribute android:completionhint android:completionhintview android:completionthreshold android:dropdownanchor android:dropdownheight android:dropdownhorizontaloffset android:dropdownselector android:dropdownverticaloffset Description This defines the hint displayed in the drop down menu. This defines the hint view displayed in the drop down menu. This defines the number of characters that the user must type before completion suggestions are displayed in a drop down menu. This is the View to anchor the auto-complete dropdown to. This specifies the basic height of the dropdown. The amount of pixels by which the drop down should be offset horizontally. This is the selector in a drop down list. The amount of pixels by which the drop down should be offset vertically.

136 android:dropdownwidth android:popupbackground This specifies the basic width of the dropdown. This sets the background. Example This example will take you through simple steps to show how to create your own Android application using Linear Layout and AutoCompleteTextView. Step Description 1 You will use Eclipse IDE to create an Android application and name it as GUIDemo3 under a package com.example.guidemo3 as explained in the Hello World Example chapter. 2 Modify src/mainactivity.java file to add a click event. 2 Modify the detault content of res/layout/activity_main.xml file to include Android UI control. 3 Define required constants in res/values/strings.xml file 4 Run the application to launch Android emulator and verify the result of the changes done in the application. Following is the content of the modified main activity filesrc/com.example.guidemo3/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.guidemo3; import android.os.bundle; import android.app.activity; import android.view.menu; import android.widget.arrayadapter; import android.widget.autocompletetextview; public class MainActivity extends Activity { AutoCompleteTextView autocompletetextview; String[] arr = { "MS SQL SERVER", "MySQL", "Oracle" protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); autocompletetextview = (AutoCompleteTextView) findviewbyid(r.id.autocompletetextview1); ArrayAdapter adapter = new ArrayAdapter (this,android.r.layout.select_dialog_item, arr); autocompletetextview.setthreshold(1); public boolean oncreateoptionsmenu(menu menu) { /* Inflate the menu; this adds items to the action bar if it is present */ getmenuinflater().inflate(r.menu.main, menu); return true;

137 Following will be the content of res/layout/activity_main.xml file: <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:layout_centerhorizontal="true" android:layout_margintop="25dp" / > <AutoCompleteTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textview2" android:layout_margintop="54dp" android:ems="10" /> </RelativeLayout> Following will be the content of res/values/strings.xml to define these new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">guidemo3</string> <string name="action_settings">settings</string> <string name="example_autocompletetextview">example showing AutoCompleteTextView</string> </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo3" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" />

138 <application android:allowbackup="true" > <activity android:name="com.example.guidemo3.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Let's try to run your GUIDemo3 application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: The following screen will appear after "m" will be typed in AutoCompleteTextView:

139 Exercise: I will recommend to try above example with different attributes of AutoCompleteTextView in Layout XML file as well at programming time to have different look and feel of the AutoCompleteTextView. Try to make it editable, change to font color, font family, width, textsize etc and see the result. You can also try above example with multiple AutoCompleteTextView controls in one activity. Button A Button is a Push-button which can be pressed, or clicked, by the user to perform an action. Button Attributes Following are the important attributes related to Button control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time. Inherited from android.widget.textview Class: Attribute android:autotext android:drawablebottom android:drawableright android:editable android:text Description If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors. This is the drawable to be drawn below the text. This is the drawable to be drawn to the right of the text. If set, specifies that this TextView has an input method. This is the Text to display. Inherited from android.view.view Class: Attribute android:background Description This is a drawable to use as the background.

140 android:contentdescription android:id android:onclick android:visibility This defines text that briefly describes content of the view. This supplies an identifier name for this view, This is the name of the method in this View's context to invoke when the view is clicked. This controls the initial visibility of the view. Example This example will take you through simple steps to show how to create your own Android application using Linear Layout and Button. Step Description 1 You will use Eclipse IDE to create an Android application and name it as GUIDemo4 under a package com.example.guidemo4 as explained in the Hello World Example chapter. 2 Modify src/mainactivity.java file to add a click event. 2 Modify the detault content of res/layout/activity_main.xml file to include Android UI control. 3 Define required constants in res/values/strings.xml file 4 Run the application to launch Android emulator and verify the result of the changes done in the application. Following is the content of the modified main activity filesrc/com.example.guidemo4/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.guidemo4; import android.os.bundle; import android.app.activity; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; import android.widget.toast; public class MainActivity extends Activity { private EditText edtext1,edtext2,edtext3; private Button protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); addlisteneronbutton(); private void addlisteneronbutton() { edtext1 = (EditText)findViewById(R.id.edittext); edtext2 = (EditText)findViewById(R.id.edittext2); edtext3 = (EditText)findViewById(R.id.edittext3); btnproduct = (Button)findViewById(R.id.button1);

141 btnproduct.setonclicklistener(new OnClickListener() public void onclick(view view) { String t1 = edtext1.gettext().tostring(); String t2 = edtext2.gettext().tostring(); String t3 = edtext3.gettext().tostring(); int i1 = Integer.parseInt(t1); int i2 = Integer.parseInt(t2); int i3 = Integer.parseInt(t3); ); int product = i1*i2*i3; Toast.makeText(getApplicationContext(), public boolean oncreateoptionsmenu(menu menu) { /* Inflate the menu; this adds items to the action bar if it is present */ getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity" > <TextView android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/example_button" /> <EditText android:id="@+id/edittext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignleft="@+id/button1" android:layout_below="@+id/textview1" android:layout_margintop="61dp" android:ems="10" android:inputtype="text" android:text="@string/enter_text1" /> <EditText android:id="@+id/edittext2" android:layout_width="fill_parent" android:layout_height="wrap_content"

142 android:layout_margintop="17dp" android:ems="10" android:inputtype="text" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margintop="14dp" android:ems="10" android:inputtype="text" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="35dp" /> </RelativeLayout> Following will be the content of res/values/strings.xml to define these new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">guidemo4</string> <string name="action_settings">settings</string> <string name="example_button">example showing Button</string> <string name="enter_text1"/> <string name="enter_text2"/> <string name="enter_text3"/> <string name="click_button">calculate product of 3 numbers</string> </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo4" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher"

143 > <activity android:name="com.example.guidemo4.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Let's try to run your GUIDemo4 application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: The following screen will appear after values are entered in 3 EditText and then the product is calculated by clicking on Button:

144 Exercise: I will recommend to try above example with different attributes of Button in Layout XML file as well at programming time to have different look and feel of the Button. Try to make it editable, change to font color, font family, width, textsize etc and see the result. You can also try above example with multiple Button controls in one activity. ImageButton A ImageButton is a AbsoluteLayout which enables you to specify the exact location of its children. This shows a button with an image (instead of text) that can be pressed or clicked by the user. ImageButton Attributes Following are the important attributes related to ImageButton control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time. Inherited from android.widget.imageview Class: Attribute android:adjustviewbounds android:baseline android:baselinealignbottom android:croptopadding android:src Description Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable. This is the offset of the baseline within this view. If true, the image view will be baseline aligned with based on its bottom edge. If true, the image will be cropped to fit within its padding. This sets a drawable as the content of this ImageView. Inherited from android.view.view Class: Attribute Description

145 android:background android:contentdescription android:id android:onclick This is a drawable to use as the background. This defines text that briefly describes content of the view. This supplies an identifier name for this view, This is the name of the method in this View's context to invoke when the view is clicked. android:visibility Example This controls the initial visibility of the view. This example will take you through simple steps to show how to create your own Android application using Linear Layout and ImageButton. Step Description 1 You will use Eclipse IDE to create an Android application and name it as GUIDemo5 under a package com.example.guidemo5 as explained in the Hello World Example chapter. 2 Modify src/mainactivity.java file to add a click event. 2 Modify the default content of res/layout/activity_main.xml file to include Android UI control. 3 Define required constants in res/values/strings.xml file 4 Run the application to launch Android emulator and verify the result of the changes done in the application. Following is the content of the modified main activity filesrc/com.example.guidemo5/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.guidemo5; import android.os.bundle; import android.app.activity; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.imagebutton; import android.widget.toast; public class MainActivity extends Activity { ImageButton protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); addlisteneronbutton(); private void addlisteneronbutton() { imgbutton = (ImageButton) findviewbyid (R.id.imageButton1); imgbutton.setonclicklistener(new OnClickListener()

146 public void onclick(view view) { Toast.makeText(MainActivity.this,"ImageButton Clicked : tutorialspoint.com", Toast.LENGTH_SHORT).show(); public boolean oncreateoptionsmenu(menu menu) { /* Inflate the menu; this adds items to the action bar if it is present */ getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity" > <TextView android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/example_imagebutton" /> <ImageButton android:id="@+id/imagebutton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignright="@+id/textview1" android:layout_below="@+id/textview1" android:layout_marginright="35dp" android:layout_margintop="32dp" android:contentdescription= "@string/android_launcher_image" android:src="@drawable/ic_launcher" /> </RelativeLayout> Following will be the content of res/values/strings.xml to define these new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">guidemo5</string> <string name="action_settings">settings</string> <string name="example_imagebutton">example showing ImageButton</string> <string name="android_launcher_image"></string> </resources>

147 Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo5" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" > <activity android:name="com.example.guidemo5.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Let's try to run your GUIDemo5 application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: The following screen will appear after ImageButton is clicked:

148 Exercise: I will recommend to try above example with different attributes of ImageButton in Layout XML file as well at programming time to have different look and feel of the ImageButton. Try to make it editable, change to font color, font family, width, textsize etc and see the result. You can also try above example with multiple ImageButton controls in one activity. CheckBox A CheckBox is an on/off switch that can be toggled by the user. You should use check-boxes when presenting users with a group of selectable options that are not mutually exclusive. CheckBox Attributes Following are the important attributes related to CheckBox control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time. Inherited from android.widget.textview Class: Attribute android:autotext android:drawablebottom android:drawableright android:editable android:text Description If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors. This is the drawable to be drawn below the text. This is the drawable to be drawn to the right of the text. If set, specifies that this TextView has an input method. This is the Text to display. Inherited from android.view.view Class: Attribute Description

149 android:background android:contentdescription android:id android:onclick This is a drawable to use as the background. This defines text that briefly describes content of the view. This supplies an identifier name for this view, This is the name of the method in this View's context to invoke when the view is clicked. android:visibility Example This controls the initial visibility of the view. This example will take you through simple steps to show how to create your own Android application using Linear Layout and CheckBox. Step Description 1 You will use Eclipse IDE to create an Android application and name it as GUIDemo6 under a package com.example.guidemo6 as explained in the Hello World Example chapter. 2 Modify src/mainactivity.java file to add a click event. 2 Modify the default content of res/layout/activity_main.xml file to include Android UI control. 3 Define required constants in res/values/strings.xml file 4 Run the application to launch Android emulator and verify the result of the changes done in the application. Following is the content of the modified main activity filesrc/com.example.guidemo5/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.guidemo6; import android.os.bundle; import android.app.activity; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.checkbox; import android.widget.toast; public class MainActivity extends Activity { private CheckBox chk1, chk2, protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // 3 methods addlisteneroncheck1(); addlisteneroncheck2(); addlisteneroncheck3(); // method for CheckBox1 - Java private void addlisteneroncheck1() { chk1 = (CheckBox) findviewbyid(r.id.checkbox1); chk2 = (CheckBox) findviewbyid(r.id.checkbox2);

150 chk3 = (CheckBox) findviewbyid(r.id.checkbox3); chk2.setonclicklistener(new OnClickListener() public void onclick(view v) { StringBuffer result = new StringBuffer(); result.append("java Selection : ").append (chk1.ischecked()); result.append("\nperl Selection : ").append (chk2.ischecked()); result.append("\npython Selection :").append (chk3.ischecked()); ); Toast.makeText(MainActivity.this, result.tostring(), Toast.LENGTH_LONG).show(); // method for CheckBox2 - Perl private void addlisteneroncheck2() { chk1 = (CheckBox) findviewbyid(r.id.checkbox1); chk2 = (CheckBox) findviewbyid(r.id.checkbox2); chk3 = (CheckBox) findviewbyid(r.id.checkbox3); chk3.setonclicklistener(new OnClickListener() public void onclick(view v) { StringBuffer result = new StringBuffer(); result.append("java Selection : ").append (chk1.ischecked()); result.append("\nperl Selection : ").append (chk2.ischecked()); result.append("\npython Selection :").append (chk3.ischecked()); ); Toast.makeText(MainActivity.this, result.tostring (),Toast.LENGTH_LONG).show(); /* method for CheckBox3 - Python */ private void addlisteneroncheck3() { // TODO Auto-generated method stub chk1 = (CheckBox) findviewbyid(r.id.checkbox1); chk2 = (CheckBox) findviewbyid(r.id.checkbox2); chk3 = (CheckBox) findviewbyid(r.id.checkbox3); chk1.setonclicklistener(new OnClickListener() public void onclick(view v) { StringBuffer result = new StringBuffer(); result.append("java Selection : ").append(chk1.ischecked());

151 result.append("\nperl Selection : ").append(chk2.ischecked()); result.append("\npython Selection :").append(chk3.ischecked()); Toast.makeText(MainActivity.this, result.tostring(), Toast.LENGTH_LONG).show(); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity" > <TextView android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/example_checkbox" /> <CheckBox android:id="@+id/checkbox1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/textview1" android:layout_below="@+id/textview1" android:layout_margintop="88dp" android:text="@string/check_one" /> <CheckBox android:id="@+id/checkbox2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/checkbox1" android:layout_below="@+id/checkbox1" android:layout_margintop="22dp" android:text="@string/check_two" /> <CheckBox

152 android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentleft="true" android:layout_margintop="24dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="39dp" /> </RelativeLayout> Following will be the content of res/values/strings.xml to define these new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">guidemo6</string> <string name="action_settings">settings</string> <string name="example_checkbox">example showing CheckBox Control</string> <string name="check_one">java</string> <string name="check_two">perl</string> <string name="check_three">python</string> <string name="example_question">worked on following Languages-</string> </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo6" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" > <activity android:name="com.example.guidemo5.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application>

153 </manifest> Let's try to run your GUIDemo6 application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: The following screen will appear after CheckBox1 i.e Java is clicked: The following screen will appear after CheckBox3 i.e Python is clicked, now it will appear for both Java(previous selection) and Perl:

154 Exercise: I will recommend to try above example with different attributes of CheckBox in Layout XML file as well at programming time to have different look and feel of the CheckBox. Try to make it editable, change to font color, font family, width, textsize etc and see the result. You can also try above example with multiple CheckBox controls in one activity. ToggleButton A ToggleButton displays checked/unchecked states as a button. It is basically an on/off button with a light indicator. ToggleButton Attributes Following are the important attributes related to ToggleButton control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time. Attribute android:disabledalpha android:textoff android:texton Description This is the alpha to apply to the indicator when disabled. This is the text for the button when it is not checked. This is the text for the button when it is checked. Inherited from android.widget.textview Class: Attribute android:autotext android:drawablebottom android:drawableright Description If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors. This is the drawable to be drawn below the text. This is the drawable to be drawn to the right of the text.

155 android:editable android:text If set, specifies that this TextView has an input method. This is the Text to display. Inherited from android.view.view Class: Attribute android:background android:contentdescription android:id android:onclick android:visibility Description This is a drawable to use as the background. This defines text that briefly describes content of the view. This supplies an identifier name for this view, This is the name of the method in this View's context to invoke when the view is clicked. This controls the initial visibility of the view. Example This example will take you through simple steps to show how to create your own Android application using Linear Layout and ToggleButton. Step Description 1 You will use Eclipse IDE to create an Android application and name it as GUIDemo7 under a package com.example.guidemo7 as explained in the Hello World Example chapter. 2 Modify src/mainactivity.java file to add a click event. 2 Modify the default content of res/layout/activity_main.xml file to include Android UI control. 3 Define required constants in res/values/strings.xml file 4 Run the application to launch Android emulator and verify the result of the changes done in the application. Following is the content of the modified main activity filesrc/com.example.guidemo7/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.guidemo7; import android.os.bundle; import android.app.activity; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.toast; import android.widget.togglebutton; public class MainActivity extends Activity { private ToggleButton togglebtn1, togglebtn2; private Button protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main);

156 addlistenerontogglebutton(); private void addlistenerontogglebutton() { togglebtn1 = (ToggleButton) findviewbyid (R.id.toggleButton1); togglebtn2 = (ToggleButton) findviewbyid (R.id.toggleButton2); btresult = (Button) findviewbyid(r.id.button1); btresult.setonclicklistener(new OnClickListener() public void onclick(view v) { StringBuffer result = new StringBuffer(); result.append("start Condition - ").append (togglebtn1.gettext()); result.append("\nstop Condition - ").append (togglebtn2.gettext()); Toast.makeText(MainActivity.this, result.tostring(), Toast.LENGTH_SHORT).show(); public boolean oncreateoptionsmenu(menu menu) { /* Inflate the menu; this adds items to the action bar if it is present */ getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity" > <TextView android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/example_togglebutton" /> <ToggleButton android:id="@+id/togglebutton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/textview1" android:layout_below="@+id/textview1" android:layout_margintop="24dp" /> <Button

157 android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginleft="19dp" android:layout_margintop="30dp" /> <ToggleButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true"/> </RelativeLayout> Following will be the content of res/values/strings.xml to define these new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">guidemo7</string> <string name="action_settings">settings</string> <string name="example_togglebutton">example showing ToggleButton</string> <string name="start_togglebutton">start</string> <string name="stop_togglebutton">stop</string> <string name="example_result">click Me</string> </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo7" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" > <activity android:name="com.example.guidemo7.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter>

158 </activity> </application> </manifest> Let's try to run your GUIDemo7 application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: The following screen will appear: The following screen will appear, conditions are shown when state of both the toggle buttons are changed: The following screen will appear, conditions are shown when state of 2nd toggle button is changed to START:

159 Exercise: I will recommend to try above example with different attributes of ToggleButton in Layout XML file as well at programming time to have different look and feel of the ToggleButton. Try to make it editable, change to font color, font family, width, textsize etc and see the result. You can also try above example with multiple ToggleButton controls in one activity. RadioButton A RadioButton has two states: either checked or unchecked.this allows the user to select one option from a set. RadioButton Attributes Following are the important attributes related to RadioButton control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time. Inherited from android.widget.textview Class: Attribute android:autotext android:drawablebottom android:drawableright android:editable android:text Description If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors. This is the drawable to be drawn below the text. This is the drawable to be drawn to the right of the text. If set, specifies that this TextView has an input method. This is the Text to display. Inherited from android.view.view Class: Attribute android:background Description This is a drawable to use as the background.

160 android:contentdescription android:id android:onclick android:visibility This defines text that briefly describes content of the view. This supplies an identifier name for this view, This is the name of the method in this View's context to invoke when the view is clicked. This controls the initial visibility of the view. Example This example will take you through simple steps to show how to create your own Android application using Linear Layout and RadioButton. Step Description 1 You will use Eclipse IDE to create an Android application and name it as GUIDemo8 under a package com.example.guidemo8 as explained in the Hello World Example chapter. 2 Modify src/mainactivity.java file to add a click event. 2 Modify the default content of res/layout/activity_main.xml file to include Android UI control. 3 Define required constants in res/values/strings.xml file 4 Run the application to launch Android emulator and verify the result of the changes done in the application. Following is the content of the modified main activity filesrc/com.example.guidemo8/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.guidemo8; import android.os.bundle; import android.app.activity; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.radiobutton; import android.widget.radiogroup; import android.widget.toast; public class MainActivity extends Activity { private RadioGroup radiogroupwebsite; private RadioButton radiobtn1; private Button protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); addlistenerradiobutton(); private void addlistenerradiobutton() { radiogroupwebsite = (RadioGroup) findviewbyid

161 (R.id.radioGroup1); btnwebsitename = (Button) findviewbyid(r.id.button1); btnwebsitename.setonclicklistener(new OnClickListener() public void onclick(view v) { // get selected radio button from radiogroupwebsite int selected = radiogroupwebsite.getcheckedradiobuttonid(); radiobtn1 = (RadioButton) findviewbyid(selected); Toast.makeText(MainActivity.this, radiobtn1.gettext(), Toast.LENGTH_SHORT).show(); public boolean oncreateoptionsmenu(menu menu) { /* Inflate the menu; this adds items to the action bar if it is present */ getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity" > <TextView android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/example_radiobutton" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/textview1" android:layout_centervertical="true" android:text="@string/website_name" /> <RadioGroup android:id="@+id/radiogroup1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/textview1" android:layout_below="@+id/textview1" android:layout_margintop="30dp" >

162 <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" /> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" /> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RadioGroup> </RelativeLayout> Following will be the content of res/values/strings.xml to define these new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">guidemo8</string> <string name="action_settings">settings</string> <string name="example_radiobutton">example showing RadioButton</string> <string name="website_name">website URL</string> <string name="website_radio0"> <string name="website_radio1"> <string name="website_radio2"> </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo8" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" > <activity android:name="com.example.guidemo8.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" />

163 <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Let's try to run your GUIDemo8 application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: It checks the 2nd radiobutton and text " is shown when Button is clicked: The following screen will appear when 3rd radiobutton is checked and text " is shown when Button is clicked::

164 Exercise: I will recommend to try above example with different attributes of RadioButton in Layout XML file as well at programming time to have different look and feel of the RadioButton. Try to make it editable, change to font color, font family, width, textsize etc and see the result. You can also try above example with multiple RadioButton controls in one activity. RadioGroup A RadioGroup class is used for set of radio buttons. If we check one radio button that belongs to a radio group, it automatically unchecks any previously checked radio button within the same group. RadioGroup Attributes Following are the important attributes related to RadioGroup control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time. Attribute android:checkedbutton Description This is the id of child radio button that should be checked by default within this radio group. Inherited from android.view.view Class: Attribute android:background android:contentdescription android:id android:onclick android:visibility Description This is a drawable to use as the background. This defines text that briefly describes content of the view. This supplies an identifier name for this view, This is the name of the method in this View's context to invoke when the view is clicked. This controls the initial visibility of the view. Example This example will take you through simple steps to show how to create your own Android application using Linear Layout and RadioGroup. Step Description 1 You will use Eclipse IDE to create an Android application and name it as GUIDemo9 under a package com.example.guidemo9 as explained in the Hello World Example chapter. 2 Modify src/mainactivity.java file to add a click event. 2 Modify the default content of res/layout/activity_main.xml file to include Android UI control. 3 Define required constants in res/values/strings.xml file 4 Run the application to launch Android emulator and verify the result of the changes done in the application. Following is the content of the modified main activity filesrc/com.example.guidemo9/mainactivity.java. This file can include each of the fundamental lifecycle methods.

165 package com.example.guidemo9; import android.os.bundle; import android.app.activity; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.radiobutton; import android.widget.radiogroup; import android.widget.toast; public class MainActivity extends Activity { private RadioGroup radiogroupcricket; private RadioGroup radiogrouptutorials; private RadioButton radiobtn1; private RadioButton radiobtn2; private Button btncricketer; private Button protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // group1 addlistenerradiogroup1(); // group2 addlistenerradiogroup2(); private void addlistenerradiogroup2() { radiogrouptutorials = (RadioGroup) findviewbyid (R.id.radioGroup2); btntutorialspoint = (Button) findviewbyid(r.id.button2); btntutorialspoint.setonclicklistener(new OnClickListener() public void onclick(view v) { // get selected radio button from radiogrouptutorials int selected = radiogrouptutorials.getcheckedradiobuttonid(); radiobtn2 = (RadioButton) findviewbyid(selected); Toast.makeText(MainActivity.this, radiobtn2.gettext(), Toast.LENGTH_SHORT).show(); ); private void addlistenerradiogroup1() { radiogroupcricket = (RadioGroup) findviewbyid (R.id.radioGroup1); btncricketer = (Button) findviewbyid(r.id.button1); btncricketer.setonclicklistener(new OnClickListener() public void onclick(view v) { // get selected radio button from radiogroupcricket

166 ); int selected = radiogroupcricket.getcheckedradiobuttonid(); radiobtn1 = (RadioButton) findviewbyid(selected); Toast.makeText(MainActivity.this, radiobtn1.gettext(), public boolean oncreateoptionsmenu(menu menu) { /* Inflate the menu; this adds items to the action bar if it is present */ getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity" > <TextView android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/example_radiogroup" /> <RadioGroup android:id="@+id/radiogroup1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentleft="true" android:layout_below="@+id/textview1" android:layout_margintop="24dp" > <RadioButton android:id="@+id/radiogroupbutton0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="@string/example_radiogroup1button0" /> <RadioButton android:id="@+id/radiogroupbutton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/example_radiogroup1button1" /> <RadioButton android:id="@+id/radiogroupbutton3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/example_radiogroup1button2" /> </RadioGroup>

167 <RadioGroup android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentright="true" android:layout_marginright="15dp" > <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" /> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" /> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RadioGroup> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="25dp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentright="true" android:layout_marginright="14dp" /> </RelativeLayout> Following will be the content of res/values/strings.xml to define these new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">guidemo9</string> <string name="action_settings">settings</string> <string name="example_radiogroup">example showing RadioGroup</string> <string name="example_radiogroup1button0">sachin</string> <string name="example_radiogroup1button1">saurav</string> <string name="example_radiogroup1button2">rahul</string> <string name="example_radiogroup2button0">mysql Tutorial</string> <string name="example_radiogroup2button1">sql Tutorial</string>

168 <string name="example_radiogroup2button2">sqlite Tutorial</string> <string name="group_button1">cricketer</string> <string name="group_button2">tutorialspoint</string> </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo9" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" > <activity android:name="com.example.guidemo9.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Let's try to run your GUIDemo9 application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: The following screen will appear, here we have 2 RadioGroups i.e. radiogroupcricket and radiogrouptutorials. The cricketer Button is clicked after checking "Rahul" Radio Button:

169 The following screen will appear if we check one radio button that belongs to radiogrouptutorials radio group, it automatically unchecks any previously checked radio button within the same radiogrouptutorials group. The tutorialspoint Button is clicked after checking "SQL Tutorial" Radio Button: Exercise: I will recommend to try above example with different attributes of RadioButton in Layout XML file as well at programming time to have different look and feel of the RadioButton. Try to make it editable, change to font color, font family, width, textsize etc and see the result. You can also try above example with multiple RadioButton controls in one activity. Create UI Controls As explained in previous chapter, a view object may have a unique ID assigned to it which will identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is:

170 To create a UI Control/View/Widget you will have to define a view/widget in the layout file and assign it a unique ID as follows: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="i am a TextView" /> </LinearLayout> Then finally create an instance of the Control object and capture it from the layout, use the following: TextView mytext = (TextView) findviewbyid(r.id.text_id);

171 CHAPTER 15 Event Handling Events are a useful way to collect data about a user's interaction with interactive components of your app, like button presses or screen touch etc. The Android framework maintains an event queue into which events are placed as they occur and then each event is removed from the queue on a first-in, first-out (FIFO) basis. You can capture these events in your program and take appropriate action as per requirements. There are following three concepts related to Android Event Management: Event Listeners: The View class is mainly involved in building up a Android GUI, same View class provides a number of Event Listeners. The Event Listener is the object that receives notification when an event happes. Event Listeners Registration: Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. Event Handlers: When an event happens and we have registered and event listener fo the event, the event listener calls the Event Handlers, which is the method that actually handles the event. Event Listeners & Event Handlers Event Handler onclick() onlongclick() onfocuschange() onkey() ontouch() Event Listener & Description OnClickListener() This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. You will use onclick() event handler to handle such event. OnLongClickListener() This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. for one or more seconds. You will use onlongclick() event handler to handle such event. OnFocusChangeListener() This is called when the widget looses its focus ie. user goes away from the view item. You will use onfocuschange() event handler to handle such event. OnFocusChangeListener() This is called when the user is focused on the item and presses or releases a hardware key on the device. You will use onkey() event handler to handle such event. OnTouchListener() This is called when the user presses the key, releases the key, or any movement gesture on the screen. You will use ontouch() event handler to handle such event.

172 onmenuitemclick() OnMenuItemClickListener() This is called when the user selects a menu item. You will use onmenuitemclick() event handler to handle such event. There are many more event listeners available as a part of View class like OnHoverListener, OnDragListener etc which may be needed for your application. So I recommend to refer official documentation for Android application development in case you are going to develop a sophisticated apps. Event Listeners Registration: Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. Though there are several tricky ways to register your event listener for any event, but I'm going to list down only top 3 ways, out of which you can use any of them based on the situation. Using an Anonymous Inner Class Activity class implements the Listener interface. Using Layout file activity_main.xml to specify event handler directly. Below section will provide you detailed examples on all the three scenarios: Event Handling Examples EVENT LISTENERS REGISTRATION USING AN ANONYMOUS INNER CLASS Here you will create an anonymous implementation of the listener and will be useful if each class is applied to a single control only and you have advantage to pass arguments to event handler. In this approach event handler methods can access private data of Activity. No reference is needed to call to Activity. But if you applied the handler to more than one control, you would have to cut and paste the code for the handler and if the code for the handler is long, it makes the code harder to maintain. Following are the simple steps to show how we will make use of separate Listener class to register and capture click event. Similar way you can implement your listener for any other required event type. Step Description 1 You will use Eclipse IDE to create an Android application and name it as EventDemo under a package com.example.eventdemo as explained in the Hello World Example chapter. 2 Modify src/mainactivity.java file to add click event listeners and handlers for the two buttons defined. 3 Modify the detault content of res/layout/activity_main.xml file to include Android UI controls. 4 Define required constants in res/values/strings.xml file 5 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.eventdemo/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.eventdemo; import android.os.bundle;

173 import android.app.activity; import android.view.menu; import android.view.view; import android.widget.button; import android.widget.textview; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); //--- find both the buttons--- Button sbutton = (Button) findviewbyid(r.id.button_s); Button lbutton = (Button) findviewbyid(r.id.button_l); // -- register click event with first button --- sbutton.setonclicklistener(new View.OnClickListener() { public void onclick(view v) { // --- find the text view -- TextView txtview = (TextView) findviewbyid(r.id.text_id); // -- change text size -- txtview.settextsize(14); ); // -- register click event with second button --- lbutton.setonclicklistener(new View.OnClickListener() { public void onclick(view v) { // --- find the text view -- TextView txtview = (TextView) findviewbyid(r.id.text_id); // -- change text size -- txtview.settextsize(24); public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/button_s" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="@string/button_small"/>

174 <Button android:layout_height="wrap_content" android:layout_width="match_parent" <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:capitalize="characters" /> </LinearLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">eventdemo</string> <string name="action_settings">settings</string> <string name="hello_world">hello world!</string> <string name="button_small">small Font</string> <string name="button_large">large Font</string> </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" > <activity android:name="com.example.guidemo.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Let's try to run your EventDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse

175 installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: Now you try to click on two buttons one by one and you will see that font of the Hello World text will change, which happens because registered click event handler method is being called against each click event. REGISTRATION USING THE ACTIVITY IMPLEMENTS LISTENER INTERFACE Here your Activity class implements the Listener interface and you put the handler method in the main Activity and then you call setonclicklistener(this). This approach is fine if your application has only a single control of that Listener type otherwise you will have to do further programming to check which control has generated event. Second you cannot pass arguments to the Listener so, again, works poorly for multiple controls. Following are the simple steps to show how we will implement Listener class to register and capture click event. Similar way you can implement your listener for any other required event type. Step Description 1 We do not need to create this application from scratch, so let's make use of above created Android application EventDemo. 2 Modify src/mainactivity.java file to add click event listeners and handlers for the two buttons defined. 3 We are not making any change in res/layout/activity_main.xml, it will remain as shown above. 4 We are also not making any change in res/values/strings.xml file, it will also remain as shown above. 5 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.eventdemo/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.eventdemo; import android.os.bundle; import android.app.activity; import android.view.menu; import android.view.view; import android.view.view.onclicklistener;

176 import android.widget.button; import android.widget.textview; public class MainActivity extends Activity implements OnClickListener protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); //--- find both the buttons--- Button sbutton = (Button) findviewbyid(r.id.button_s); Button lbutton = (Button) findviewbyid(r.id.button_l); // -- register click event with first button --- sbutton.setonclicklistener(this); // -- register click event with second button --- lbutton.setonclicklistener(this); //--- Implement the OnClickListener callback public void onclick(view v) { if(v.getid() == R.id.button_s) { // --- find the text view -- TextView txtview = (TextView) findviewbyid(r.id.text_id); // -- change text size -- txtview.settextsize(14); return; if(v.getid() == R.id.button_l) { // --- find the text view -- TextView txtview = (TextView) findviewbyid(r.id.text_id); // -- change text size -- txtview.settextsize(24); public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; Now again let's try to run your EventDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

177 Now you try to click on two buttons one by one and you will see that font of the Hello World text will change, which happens because registered click event handler method is being called against each click event. REGISTRATION USING LAYOUT FILE ACTIVITY_MAIN.XML Here you put your event handlers in Activity class without implementing a Listener interface or call to any listener method. Rather you will use the layout file (activity_main.xml) to specify the handler method via the android:onclick attribute for click event. You can control click events differently for different control by passing different event handler methods. The event handler method must have a void return type and take a View as an argument. However, the method name is arbitrary, and the main class need not implement any particular interface. This approach does not allow you to pass arguments to Listener and for the Android developers it will be difficult to know which method is the handler for which control until they look into activity_main.xml file. Second, you can not handle any other event except click event using this approach. Following are the simple steps to show how we can make use of layout file Main.xml to register and capture click event. Step Description 1 We do not need to create this application from scratch, so let's make use of above created Android application EventDemo. 2 Modify src/mainactivity.java file to add click event listeners and handlers for the two buttons defined. 3 Modify layout file res/layout/activity_main.xml, to specify event handlers for the two buttons. 4 We are also not making any change in res/values/strings.xml file, it will also remain as shown above. 5 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.eventdemo/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.eventdemo; import android.os.bundle; import android.app.activity; import android.view.menu;

178 import android.view.view; import android.widget.button; import android.widget.textview; public class MainActivity extends protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); //--- Implement the event handler for the first button. public void dosmall(view v) { // --- find the text view -- TextView txtview = (TextView) findviewbyid(r.id.text_id); // -- change text size -- txtview.settextsize(14); return; //--- Implement the event handler for the second button. public void dolarge(view v) { // --- find the text view -- TextView txtview = (TextView) findviewbyid(r.id.text_id); // -- change text size -- txtview.settextsize(24); public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file. Here we have to addandroid:onclick="methodname" for both the buttons, which will register given method names as click event handlers. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/button_s" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="@string/button_small" android:onclick="dosmall"/> <Button android:id="@+id/button_l" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="@string/button_large" android:onclick="dolarge"/>

179 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:capitalize="characters" /> </LinearLayout> Again let's try to run your EventDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: Now you try to click on two buttons one by one and you will see that font of the Hello World text will change, which happens because registered click event handler method is being called against each click event. Exercise: I will recommend to try writing different event handlers for different event types and understand exact difference in different event types and their handling. Events related to menu, spinner, pickers widgets are little different but they are also based on the same concepts as explained above.

180 CHAPTER 16 Styles and Themes If you already know about Cascading Style Sheet (CSS) in web design then to understand Android Style also works very similar way. There are number of attributes associated with each Android widget which you can set to change your application look and feel. A style can specify properties such as height, padding, font color, font size, background color, and much more. You can specify these attributes in Layout file as follows: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:capitalize="characters" android:textcolor="#00ff00" android:typeface="monospace" android:text="@string/hello_world" /> </LinearLayout> But this way we need to define style attributes for every attribute separately which is not good for source code maintenance point of view. So we work with styles by defining them in separate file as explained below.

181 Defining Styles A style is defined in an XML resource that is separate from the XML that specifies the layout. This XML file resides under res/values/ directory of your project and will have <resources> as the root node which is mandatory for the style file. The name of the XML file is arbitrary, but it must use the.xml extension. You can define multiple styles per file using <style> tag but each style will have its name that uniquely identifies the style. Android style attributes are set using <item> tag as shown below: <?xml version="1.0" encoding="utf-8"?> <resources> <style name="customfontstyle"> <item name="android:layout_width">fill_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:capitalize">characters</item> <item name="android:typeface">monospace</item> <item name="android:textsize">12pt</item> <item name="android:textcolor">#00ff00</item>/> </style> </resources> The value for the <item> can be a keyword string, a hex color, a reference to another resource type, or other value depending on the style property. Using Styles Once your style is defined, you can use it in your XML Layout file using style attribute as follows: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text_id" style="@style/customfontstyle" android:text="@string/hello_world" /> </LinearLayout> To understand the concept related to Android Style, you can check Style Demo Example given below:

182 Following example demonstrates how you can use a Style for individual elements. Let's start with creating a simple Android application as per the following steps: Step 1 Description You will use Eclipse IDE to create an Android application and name it as StyleDemo under a package com.example.styledemo as explained in the Hello World Example chapter. 2 Modify src/mainactivity.java file to add click event listeners and handlers for the two buttons defined. 3 Define your style in global style file res/values/style.xml to define custom attributes for a button. 4 Modify the detault content of res/layout/activity_main.xml file to include a set of Android UI controls and make use of the defined style. 5 Define required constants in res/values/strings.xml file 6 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.styledemo/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.styledemo; import android.os.bundle; import android.app.activity; import android.view.menu; import android.view.view; import android.widget.button; import android.widget.textview; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); //--- find both the buttons--- Button sbutton = (Button) findviewbyid(r.id.button_s); Button lbutton = (Button) findviewbyid(r.id.button_l); // -- register click event with first button --- sbutton.setonclicklistener(new View.OnClickListener() { public void onclick(view v) { // --- find the text view -- TextView txtview = (TextView) findviewbyid(r.id.text_id); // -- change text size -- txtview.settextsize(20); ); // -- register click event with second button --- lbutton.setonclicklistener(new View.OnClickListener() { public void onclick(view v) { // --- find the text view -- TextView txtview = (TextView) findviewbyid(r.id.text_id); // -- change text size -- txtview.settextsize(24);

183 public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/values/style.xml file which will have addition stylecustombuttonstyle defined: <resources> <!-- Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vxx/styles.xml on newer devices. --> <style name="appbasetheme" parent="android:theme.light"> <!-- Theme customizations available in newer API levels can go in res/values-vxx/styles.xml, while customizations related to backward-compatibility can go here. --> </style> <!-- Application theme. --> <style name="apptheme" parent="appbasetheme"> <!-- All customizations that are NOT specific to a particular API-level can go here. --> </style> <!-- Custom Style defined for the buttons. --> <style name="custombuttonstyle"> <item name="android:layout_width">100dp</item> <item name="android:layout_height">38dp</item> <item name="android:capitalize">characters</item> <item name="android:typeface">monospace</item> <item name="android:shadowdx">1.2</item> <item name="android:shadowdy">1.2</item> <item name="android:shadowradius">2</item> <item name="android:textcolor">#494948</item>/> <item name="android:gravity" >center</item> <item name="android:layout_margin" >3dp</item> <item name="android:textsize" >5pt</item> <item name="android:shadowcolor" >#000000</item> </style> </resources> Following will be the content of res/layout/activity_main.xml file: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >

184 <Button android:onclick="dosmall"/> <Button android:onclick="dolarge"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:capitalize="characters" /> </LinearLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">styledemo</string> <string name="action_settings">settings</string> <string name="hello_world">hello world!</string> <string name="button_small">small Font</string> <string name="button_large">large Font</string> </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" > <activity android:name="com.example.guidemo.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter>

185 </activity> </application> </manifest> Let's try to run your StyleDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: Style Inheritance Android supports style Inheritance in very much similar way as cascading style sheet in web design. You can use this to inherit properties from an existing style and then define only the properties that you want to change or add. Its simple, to create a new style LargeFont that inherits the CustomFontStyle style defined above, but make the font size big, you can author the new style like this: <?xml version="1.0" encoding="utf-8"?> <resources> <style name="customfontstyle.largefont"> <item name="android:textsize">20ps</item> </style> </resources> You can reference this new style in your XML Layout file. You can continue inheriting like this as many times as you'd like, by chaining names with periods. For example, you can extend FontStyle.LargeFont to be Red, with: <?xml version="1.0" encoding="utf-8"?> <resources> <style name="customfontstyle.largefont.red"> <item name="android:textcolor">#ff0000</item>/>

186 </style> </resources> This technique for inheritance by chaining together names only works for styles defined by your own resources. You can't inherit Android built-in styles this way. To reference an Android built-in style, such as TextAppearance, you must use the parent attribute as shown below: <?xml version="1.0" encoding="utf-8"?> <resources> <style name="customfontstyle" <item name="android:layout_width">fill_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:capitalize">characters</item> <item name="android:typeface">monospace</item> <item name="android:textsize">12pt</item> <item name="android:textcolor">#00ff00</item>/> </style> </resources> Android Themes Hope you understood the concept of Style, so now let's try to understand what is a Theme. A theme is nothing but an Android style applied to an entire Activity or application, rather than an individual View. Thus, when a style is applied as a theme, every View in the Activity or application will apply each style property that it supports. For example, you can apply the same CustomFontStyle style as a theme for an Activity and then all text inside that Activity will have green monospace font. To set a theme for all the activities of your application, open the AndroidManifest.xml file and edit the<application> tag to include the android:theme attribute with the style name. For example: <application android:theme="@style/customfontstyle"> But if you want a theme applied to just one Activity in your application, then add the android:theme attribute to the <activity> tag only. For example: <activity android:theme="@style/customfontstyle"> There are number of default themes defined by Android which you can use directly or inherit them using parent attribute as follows: <style name="customtheme" parent="android:theme.light">... </style> To understand the concept related to Android Theme, you can check Theme Demo Example given below:

187 Following example demonstrates how you can use a theme for an application. For demo purpose we will modify our default AppTheme wehere default text, its size, family, shadow etc will be changed. Let's start with creating a simple Android application as per the following steps: Step 1 Description You will use Eclipse IDE to create an Android application and name it as ThemeDemo under a package com.example.themedemo as explained in the Hello World Example chapter. 2 Modify src/mainactivity.java file to add click event listeners and handlers for the two buttons defined. 3 4 Define your style in global style file res/values/style.xml to define custom attributes for a button and change default theme of the application to play with the text. Modify the detault content of res/layout/activity_main.xml file to include a set of Android UI controls and make use of the defined style. 5 Define required constants in res/values/strings.xml file 6 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.themedemo/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.themedemo; import android.os.bundle; import android.app.activity; import android.view.menu; import android.view.view; import android.widget.button; import android.widget.textview; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); //--- find both the buttons--- Button sbutton = (Button) findviewbyid(r.id.button_s); Button lbutton = (Button) findviewbyid(r.id.button_l); // -- register click event with first button --- sbutton.setonclicklistener(new View.OnClickListener() { public void onclick(view v) { // --- find the text view -- TextView txtview = (TextView) findviewbyid(r.id.text_id); // -- change text size -- txtview.settextsize(20); ); // -- register click event with second button --- lbutton.setonclicklistener(new View.OnClickListener() { public void onclick(view v) { // --- find the text view -- TextView txtview = (TextView) findviewbyid(r.id.text_id); // -- change text size --

188 ); public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/values/style.xml file which will have addition stylecustombuttonstyle defined: <resources> <!-- Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vxx/styles.xml on newer devices. --> <style name="appbasetheme" parent="android:theme.light"> <!-- Theme customizations available in newer API levels can go in res/values-vxx/styles.xml, while customizations related to backward-compatibility can go here. --> </style> <!-- Application theme. --> <style name="apptheme" parent="appbasetheme"> <!-- All customizations that are NOT specific to a particular API-level can go here. --> <item name="android:capitalize">characters</item> <item name="android:typeface">monospace</item> <item name="android:shadowdx">1.2</item> <item name="android:shadowdy">1.2</item> <item name="android:shadowradius">2</item> <item name="android:textcolor">#494948</item>/> <item name="android:gravity" >center</item> <item name="android:layout_margin" >3dp</item> <item name="android:textsize" >5pt</item> <item name="android:shadowcolor" >#000000</item> </style> <!-- Custom Style defined for the buttons. --> <style name="custombuttonstyle"> <item name="android:layout_width">100dp</item> <item name="android:layout_height">38dp</item> </style> </resources> Following will be the content of res/layout/activity_main.xml file: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent"

189 android:orientation="vertical" > <Button android:onclick="dosmall"/> <Button android:onclick="dolarge"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:capitalize="characters" /> </LinearLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">themedemo</string> <string name="action_settings">settings</string> <string name="hello_world">hello world!</string> <string name="button_small">small Font</string> <string name="button_large">large Font</string> </resources> Following is the default content of AndroidManifest.xml. Here we do not need to change anything because we kept out theme name unchanged. But if you define fresh new theme or inherit a default them with different name then you will have to replace AppTheme name with the new them name. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="com.example.guidemo.mainactivity" android:label="@string/app_name" > <intent-filter>

190 <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Let's try to run your ThemeDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: Default Styles & Themes The Android platform provides a large collection of styles and themes that you can use in your applications. You can find a reference of all available styles in the R.style class. To use the styles listed here, replace all underscores in the style name with a period. For example, you can apply the Theme_NoTitleBar theme with "@android:style/theme.notitlebar". You can see the following source code for Android styles and themes: Android Styles (styles.xml) Android Themes (themes.xml)

191 CHAPTER 17 Custom Components Android offers a great list of pre-built widgets like Button, TextView, EditText, ListView, CheckBox, RadioButton, Gallery, Spinner, AutoCompleteTextView etc. which you can use directly in your Android application development, but there may be a situation when you are not satisfied with existing functionality of any of the available widgets. Android provides you with means of creating your own custom components which you can customized to suit your needs. If you only need to make small adjustments to an existing widget or layout, you can simply subclass the widget or layout and override its methods which will give you precise control over the appearance and function of a screen element. This tutorial explains you how to create custom Views and use them in your application using simple and easy steps. Creating a Simple Custom Component The simplest way to create your custom component is to extend an existing widget class or subclass with your own class if you want to extend the functionality of existing widget like Button, TextView, EditText, ListView, CheckBox etc. otherwise you can do everything yourself by starting with theandroid.view.view class. At its simplest form you will have to write your constructors corresponding to all the constructors of the base class. For example if you are going to extend TextView to create a DateView then following three constructors will be created for DateView class: public class DateView extends TextView { public DateView(Context context) { super(context); //--- Additional custom code -- public DateView(Context context, AttributeSet attrs) { super(context, attrs); //--- Additional custom code --

192 public DateView(Context context, AttributeSet attrs, int defstyle) { super(context, attrs, defstyle); //--- Additional custom code -- Because you have created DateView as child of TextView so it will have access on all the attributes, methods and events related to TextView and you will be able to use them without any further implementation. You will implement additional custom functionality inside your own code as explained in the given examples below. If you have requirement for implementing custom drawing/sizing for your custom widgets then you need to override onmeasure(int widthmeasurespec, int heightmeasurespec) and ondraw(canvas canvas) methods. If you are not going to resize or change the shape of your built-in component then you do not need either of these methods in your custom component. The onmeasure() method coordinate with the layout manager to report the widget's width and height, and you need to call setmeasureddimension(int width, int height) from inside this method to report the dimensions. You can then execute your custom drawing inside the ondraw(canvas canvas) method, where android.graphis.canvas is pretty similar to its counterpart in Swing, and has methods such as drawrect(), drawline(), drawstring(), drawbitmap() etc. which you can use to draw your component. Once you are done with the implementation of a custom component by extending existing widget, you will be able to instantiate these custom components in two ways in your application development: INSTANTIATE USING CODE INSIDE ACTIVITY CLASS It is very similar way of instantiating custom component the way you instantiate built-in widget in your activity class. For example you can use following code to instantiate above defined custom protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); DateView dateview = new DateView(this); setcontentview(dateview); Check this below given example to understand how to Instantiate a Basic Android Custom Component using code inside an activity: Instantiate a Basic Android Custom Component(using code) Following example shows you how to define a simple Android custom component and then how to instantiate it inside activity code without using layout file. Step Description

193 1 2 3 You will use Eclipse IDE to create an Android application and name it as DateViewDemounder a package com.example.dateviewdemo as explained in the Hello World Examplechapter. Create src/dateview.java file and add the code to define your custom component. It will extend TextView and will have additional functionality to show current date. Modify src/mainactivity.java file and add the code to create DateView instance and usesetcontentview() method to set it in the layout. 4 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following will be the content of new file src/com.example.dateviewdemo/dateview.java, which will have additional functionality to show current date: package com.example.dateviewdemo; import java.text.simpledateformat; import java.util.calendar; import android.content.context; import android.util.attributeset; import android.widget.textview; public class DateView extends TextView { public DateView(Context context) { super(context); setdate(); public DateView(Context context, AttributeSet attrs) { super(context, attrs); setdate(); public DateView(Context context, AttributeSet attrs, int defstyle) { super(context, attrs, defstyle); setdate(); private void setdate() { SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd"); String today = dateformat.format(calendar.getinstance().gettime()); settext(today); // self = DateView is a subclass of TextView Following is the content of the modified main activity filesrc/com.example.dateviewdemo/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.dateviewdemo; import android.os.bundle; import android.app.activity; import android.view.menu; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate);

194 setcontentview(r.layout.activity_main); //-- Create DateView instance and set it in layout. DateView dateview = new DateView(this); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the // action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </RelativeLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">dateviewdemo</string> <string name="action_settings">settings</string> <string name="hello_world">hello world!</string> </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" />

195 <application android:allowbackup="true" > <activity android:name="com.example.guidemo.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Let's try to run your DateViewDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: INSTANTIATE USING LAYOUT XML FILE Traditionally you use Layout XML file to instantiate your built-in widgets, same concept will apply on your custom widgets as well so you will be able to instantiate your custom component using Layout XML file as explained below. Here com.example.dateviewdemo is the package where you have put all the code related to DateView class and DateView is Java class name where you have put complete logic of your custom component. <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin"

196 tools:context=".mainactivity" > <com.example.dateviewdemo.dateview android:layout_width="match_parent" android:layout_height="wrap_content" android:textcolor="#fff" android:textsize="40sp" android:background="#000" /> </RelativeLayout> It is important to note here that we are using all TextView attributes along with custom component without any change. Similar way you will be able to use all the events, and methods along with DateView component. Check this example to understand how to Instantiate a Basic Android Custom Component using Layout XML file. Instantiate a Basic Android Custom Component (using Layout XML file) Following example shows you how to define a simple Android custom component and then how to instantiate it inside activity code without using layout file. Step Description You will use Eclipse IDE to create an Android application and name it as DateViewDemounder a package com.example.dateviewdemo as explained in the Hello World Examplechapter. Create src/dateview.java file and add the code to define your custom component. It will extend TextView and will have additional functionality to show current date. Modify res/layout/activity_main.xml file and add the code to create DateView instance along with few default attributes. 4 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following will be the content of new file src/com.example.dateviewdemo/dateview.java, which will have additional functionality to show current date: package com.example.dateviewdemo; import java.text.simpledateformat; import java.util.calendar;

197 import android.content.context; import android.util.attributeset; import android.widget.textview; public class DateView extends TextView { public DateView(Context context) { super(context); setdate(); public DateView(Context context, AttributeSet attrs) { super(context, attrs); setdate(); public DateView(Context context, AttributeSet attrs, int defstyle) { super(context, attrs, defstyle); setdate(); private void setdate() { SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd"); String today = dateformat.format(calendar.getinstance().gettime()); settext(today); // self = DateView is a subclass of TextView Following is the content of the modified main activity filesrc/com.example.dateviewdemo/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.dateviewdemo; import android.os.bundle; import android.app.activity;

198 import android.view.menu; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the // action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/layout/activity_main.xml file: <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity" > <com.example.dateviewdemo.dateview android:layout_width="match_parent" android:layout_height="wrap_content" android:textcolor="#fff"

199 android:textsize="40sp" android:background="#000" /> </RelativeLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">dateviewdemo</string> <string name="action_settings">settings</string> <string name="hello_world">hello world!</string> </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" > <activity android:name="com.example.guidemo.mainactivity"

200 > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Let's try to run your DateViewDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: Custom Component with Custom Attributes We have seen how we can extend functionality of built-in widgets but in both the examples given above we saw that extended component can make use of all the default attributes of its parent class. But consider a situation when you want to create your own attribute from scratch. Below is a simple procedure to create and use new attributes for Android Custom components. Consider we want to introduce three attributes and will use them as shown below: <com.example.dateviewdemo.dateview android:layout_width="match_parent" android:layout_height="wrap_content" android:textcolor="#fff" android:textsize="40sp"

201 custom:delimiter="-" custom:fancytext="true" /> STEP 1 The first step to enable us to use our custom attributes is to define them in a new xml file underres/values/ and call it attrs.xml. Let's have a look on an example attrs.xml file: <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="dateview"> <attr name="delimiter" format="string"/> <attr name="fancytext" format="boolean"/> </declare-styleable> </resources> Here the name=value is what we want to use in our Layout XML file as attribute, and the format=type is the type of attribute. STEP 2 Your second step will be to read these attributes from Layout XML file and set them for the component. This logic will go in the constructors that get passed an AttributeSet, since that is what contains the XML attributes. To read the values in the XML, you need to first create a TypedArray from theattributeset, then use that to read and set the values as shown in the below example code: TypedArray a = context.obtainstyledattributes(attrs, R.styleable.DateView); final int N = a.getindexcount(); for (int i = 0; i < N; ++i) { int attr = a.getindex(i); switch (attr) { case R.styleable.DateView_delimiter: String delimiter = a.getstring(attr); //...do something with delimiter... break; case R.styleable.DateView_fancyText: boolean fancytext = a.getboolean(attr, false);

202 //...do something with fancytext... break; a.recycle(); STEP 3 Finally you can use your defined attributes in your Layout XML file as follows: <RelativeLayout xmlns:android=" xmlns:tools=" xmlns:custom=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity" > <com.example.dateviewdemo.dateview android:layout_width="match_parent" android:layout_height="wrap_content" android:textcolor="#fff" android:textsize="40sp" custom:delimiter="-" custom:fancytext="true" /> </RelativeLayout> The important part isxmlns:custom=" Note thathttp://schemas.android.com/apk/res/ will remain as is, but last part will be set to your package name and also that you can use anything after xmlns:, in this example I used custom, but you could use any name you like. Check this below given example to understand how to Create Custom Attributes for Android Custom Componentwith simple steps. Create Custom Attributes for Android Custom Component

203 Following example shows you how to define a simple Android custom component with custom attributes. Step Description 1 You will use Eclipse IDE to create an Android application and name it as DateViewDemounder a package com.example.dateviewdemo as explained in the Hello World Examplechapter. 2 Create an XML res/values/attrs.xml file to define new attributes alongwith their data type. 3 4 Create src/dateview.java file and add the code to define your custom component. It will extend TextView and will have additional functionality to show current date. You will provide attributes parsing logic in of the constructors having AttributeSet as a parameter. Modify res/layout/activity_main.xml file and add the code to create DateView instance along with few default attributes and new attributes. 5 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.dateviewdemo/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.dateviewdemo; import android.os.bundle; import android.app.activity; import android.view.menu; public class MainActivity extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the // action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; Following will be the content of res/values/attrs.xml file: <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="dateview"> <attr name="delimiter" format="string"/> <attr name="fancytext" format="boolean"/> </declare-styleable> </resources> Following will be the content of new file src/com.example.dateviewdemo/dateview.java, which will have additional functionality to show current date: package com.example.dateviewdemo;

204 import java.text.simpledateformat; import java.util.calendar; import android.content.context; import android.content.res.typedarray; import android.graphics.color; import android.util.attributeset; import android.util.log; import android.widget.textview; public class DateView extends TextView { public String delimiter; public boolean fancytext; public DateView(Context context) { super(context); setdate(); public DateView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainstyledattributes(attrs, R.styleable.DateView ); final int N = a.getindexcount(); for (int i = 0; i < N; ++i) { int attr = a.getindex(i); switch (attr) { case R.styleable.DateView_delimiter: delimiter = a.getstring(attr); setdate(); break; case R.styleable.DateView_fancyText: fancytext = a.getboolean(attr, false); fancytext(); break; a.recycle(); public DateView(Context context, AttributeSet attrs, int defstyle) { super(context, attrs, defstyle); setdate(); private void setdate() { SimpleDateFormat dateformat = new SimpleDateFormat("yyyy" + delimiter + "MM" + delimiter + "dd"); String today = dateformat.format(calendar.getinstance().gettime()); settext(today); // self = DateView = subclass of TextView private void fancytext() { if( this.fancytext){ setshadowlayer(9, 1, 1, Color.rgb(44, 44, 40));

205 Following will be the content of res/layout/activity_main.xml file: <RelativeLayout xmlns:android=" xmlns:tools=" xmlns:custom=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity" > <com.example.dateviewdemo.dateview android:layout_width="match_parent" android:layout_height="wrap_content" android:textcolor="#fff" android:textsize="40sp" custom:delimiter="-" custom:fancytext="true" /> </RelativeLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">dateviewdemo</string> <string name="action_settings">settings</string> <string name="hello_world">hello world!</string> </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.guidemo" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" > <activity android:name="com.example.guidemo.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" />

206 <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Let's try to run your DateViewDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: NotificationCompat.Builder setdefaults (int defaults) Set the default notification options that will be used. NotificationCompat.Builder setlargeicon (Bitmap icon) Set the large icon that is shown in the ticker and notification. NotificationCompat.Builder setnumber (int number) Set the large number at the right-hand side of the notification. NotificationCompat.Builder setongoing (boolean ongoing) Set whether this is an ongoing notification. NotificationCompat.Builder setsmallicon (int icon) Set the small icon to use in the notification layouts. NotificationCompat.Builder setstyle (NotificationCompat.Style style) Add a rich notification style to be applied at build time. NotificationCompat.Builder setticker (CharSequence tickertext) Set the text that is displayed in the status bar when the notification first arrives. NotificationCompat.Builder setvibrate (long[] pattern) Set the vibration pattern to use. NotificationCompat.Builder setwhen (long when) Set the time that the event occurred. Notifications in the panel are sorted by this time.

207 Example Following example shows the functionality of a Android notification using a NotificationCompat.BuilderClass which has been introduced in Android 4.1. Step Description You will use Eclipse IDE to create an Android application and name it as NotificationDemounder a package com.example.notificationdemo. While creating this project, make sure youtarget SDK and Compile With at the latest version of Android SDK to use higher levels of APIs. Modify src/mainactivity.java file and add the code to define three methods startnotification(), cancelnotification() and updatenotification() to cover maximum functionality related to Android notifications. Create a new Java file src/notificationview.java, which will be used to display new layout as a part of new activity which will be started when user will click any of the notifications Copy image woman.png in res/drawable-* folders and this image will be used as Notification icons. You can use images with different resolution in case you want to provide them for different devices. 5 Modify layout XML file res/layout/activity_main.xml to add three buttons in linear layout. 6 Create a new layout XML file res/layout/notification.xml. This will be used as layout file for new activity which will start when user will click any of the notifications. 7 Modify res/values/strings.xml to define required constant values 8 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity filesrc/com.example.notificationdemo/mainactivity.java. This file can include each of the fundamental lifecycle methods. package com.example.notificationdemo; import android.os.bundle; import android.app.activity; import android.app.notificationmanager; import android.app.pendingintent; import android.app.taskstackbuilder; import android.content.context; import android.content.intent; import android.support.v4.app.notificationcompat; import android.util.log; import android.view.view; import android.widget.button; public class MainActivity extends Activity { private NotificationManager mnotificationmanager; private int notificationid = 100; private int nummessages = 0; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); Button startbtn = (Button) findviewbyid(r.id.start); startbtn.setonclicklistener(new View.OnClickListener() { public void onclick(view view) { displaynotification(); );

208 Button cancelbtn = (Button) findviewbyid(r.id.cancel); cancelbtn.setonclicklistener(new View.OnClickListener() { public void onclick(view view) { cancelnotification(); ); Button updatebtn = (Button) findviewbyid(r.id.update); updatebtn.setonclicklistener(new View.OnClickListener() { public void onclick(view view) { updatenotification(); ); protected void displaynotification() { Log.i("Start", "notification"); /* Invoking the default notification service */ NotificationCompat.Builder mbuilder = new NotificationCompat.Builder(this); mbuilder.setcontenttitle("new Message"); mbuilder.setcontenttext("you've received new message."); mbuilder.setticker("new Message Alert!"); mbuilder.setsmallicon(r.drawable.woman); /* Increase notification number every time a new notification arrives */ mbuilder.setnumber(++nummessages); /* Creates an explicit intent for an Activity in your app */ Intent resultintent = new Intent(this, NotificationView.class); TaskStackBuilder stackbuilder = TaskStackBuilder.create(this); stackbuilder.addparentstack(notificationview.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackbuilder.addnextintent(resultintent); PendingIntent resultpendingintent = stackbuilder.getpendingintent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); mbuilder.setcontentintent(resultpendingintent); mnotificationmanager = (NotificationManager) getsystemservice(context.notification_service); /* notificationid allows you to update the notification later on. */ mnotificationmanager.notify(notificationid, mbuilder.build()); protected void cancelnotification() { Log.i("Cancel", "notification"); mnotificationmanager.cancel(notificationid); protected void updatenotification() { Log.i("Update", "notification");

209 /* Invoking the default notification service */ NotificationCompat.Builder mbuilder = new NotificationCompat.Builder(this); mbuilder.setcontenttitle("updated Message"); mbuilder.setcontenttext("you've got updated message."); mbuilder.setticker("updated Message Alert!"); mbuilder.setsmallicon(r.drawable.woman); /* Increase notification number every time a new notification arrives */ mbuilder.setnumber(++nummessages); /* Creates an explicit intent for an Activity in your app */ Intent resultintent = new Intent(this, NotificationView.class); TaskStackBuilder stackbuilder = TaskStackBuilder.create(this); stackbuilder.addparentstack(notificationview.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackbuilder.addnextintent(resultintent); PendingIntent resultpendingintent = stackbuilder.getpendingintent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); mbuilder.setcontentintent(resultpendingintent); mnotificationmanager = (NotificationManager) getsystemservice(context.notification_service); /* Update the existing notification using same notification ID */ mnotificationmanager.notify(notificationid, mbuilder.build()); Following is the content of the modified main activity filesrc/com.example.notificationdemo/notificationview.java. package com.example.notificationdemo; import android.os.bundle; import android.app.activity; public class NotificationView extends public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.notification); Following will be the content of res/layout/activity_main.xml file: <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >

210 <Button android:layout_width="fill_parent" android:layout_height="wrap_content" <Button android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> Following will be the content of res/layout/notification.xml file: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="400dp" android:text="hi, Your Detailed notification view goes here..." /> </LinearLayout> Following will be the content of res/values/strings.xml to define two new constants: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">notificationdemo</string> <string name="action_settings">settings</string> <string name="hello_world">hello world!</string> <string name="start_note">start Notification</string> <string name="cancel_note">cancel Notification</string> <string name="update_note">update Notification</string> </resources> Following is the default content of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.notificationdemo" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="17" android:targetsdkversion="17" /> <application android:allowbackup="true"

211 > <activity android:name="com.example.notificationdemo.mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <activity android:name=".notificationview" android:label="details of notification" android:parentactivityname=".mainactivity"> <meta-data android:name="android.support.parent_activity" android:value=".mainactivity"/> </activity> </application> </manifest> Let's try to run your NotificationDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window: Now click Start Notification button, you will see at the top a message "New Message Alert!" will display momentarily and after that you will have following screen having a small icon at the top left corner.

212 Now lets expand the view, long click on the small icon, after a second it will display date information and this is the time when you should drag status bar down without releasing mouse. You will see status bar will expand and you will get following screen: Now let's try to click on the image icon, this will launch your new activity which you have set using intent and you will have following screen:

Group B: Assignment No 8. Title of Assignment: To verify the operating system name and version of Mobile devices.

Group B: Assignment No 8. Title of Assignment: To verify the operating system name and version of Mobile devices. Group B: Assignment No 8 Regularity (2) Performance(5) Oral(3) Total (10) Dated Sign Title of Assignment: To verify the operating system name and version of Mobile devices. Problem Definition: Write a

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Android

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Android Cover page About the Tutorial Android is an open-source, Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led

More information

Android Application Development. By : Shibaji Debnath

Android Application Development. By : Shibaji Debnath Android Application Development By : Shibaji Debnath About Me I have over 10 years experience in IT Industry. I have started my career as Java Software Developer. I worked in various multinational company.

More information

Android HelloWorld - Example. Tushar B. Kute,

Android HelloWorld - Example. Tushar B. Kute, Android HelloWorld - Example Tushar B. Kute, http://tusharkute.com Anatomy of Android Application Anatomy of Android Application Java This contains the.java source files for your project. By default, it

More information

Basics of Android Operating System

Basics of Android Operating System Basics of Android Operating System Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance,

More information

UNIT:2 Introduction to Android

UNIT:2 Introduction to Android UNIT:2 Introduction to Android 1 Syllabus 2.1 Overview of Android 2.2 What does Android run On Android Internals? 2.3 Android for mobile apps development 2.5 Environment setup for Android apps Development

More information

ANDROID SERVICES, BROADCAST RECEIVER, APPLICATION RESOURCES AND PROCESS

ANDROID SERVICES, BROADCAST RECEIVER, APPLICATION RESOURCES AND PROCESS ANDROID SERVICES, BROADCAST RECEIVER, APPLICATION RESOURCES AND PROCESS 1 Instructor: Mazhar Hussain Services A Service is an application component that can perform long-running operations in the background

More information

Introduction To Android

Introduction To Android Introduction To Android Mobile Technologies Symbian OS ios BlackBerry OS Windows Android Introduction to Android Android is an operating system for mobile devices such as smart phones and tablet computers.

More information

Android Development Tutorial. Yi Huang

Android Development Tutorial. Yi Huang Android Development Tutorial Yi Huang Contents What s Android Android architecture Android software development Hello World on Android More 2 3 What s Android Android Phones Sony X10 HTC G1 Samsung i7500

More information

MODULE 2: GETTING STARTED WITH ANDROID PROGRAMMING

MODULE 2: GETTING STARTED WITH ANDROID PROGRAMMING This document can be downloaded from www.chetanahegde.in with most recent updates. 1 MODULE 2: GETTING STARTED WITH ANDROID PROGRAMMING Syllabus: What is Android? Obtaining the required tools, Anatomy

More information

Android Application Development

Android Application Development Android Application Development Octav Chipara What is Android A free, open source mobile platform A Linux-based, multiprocess, multithreaded OS Android is not a device or a product It s not even limited

More information

UNDERSTANDING ACTIVITIES

UNDERSTANDING ACTIVITIES Activities Activity is a window that contains the user interface of your application. An Android activity is both a unit of user interaction - typically filling the whole screen of an Android mobile device

More information

EMBEDDED SYSTEMS PROGRAMMING Android Services

EMBEDDED SYSTEMS PROGRAMMING Android Services EMBEDDED SYSTEMS PROGRAMMING 2016-17 Android Services APP COMPONENTS Activity: a single screen with a user interface Broadcast receiver: responds to system-wide broadcast events. No user interface Service:

More information

INTRODUCTION TO ANDROID

INTRODUCTION TO ANDROID INTRODUCTION TO ANDROID 1 Niv Voskoboynik Ben-Gurion University Electrical and Computer Engineering Advanced computer lab 2015 2 Contents Introduction Prior learning Download and install Thread Android

More information

Services. Marco Ronchetti Università degli Studi di Trento

Services. Marco Ronchetti Università degli Studi di Trento 1 Services Marco Ronchetti Università degli Studi di Trento Service An application component that can perform longrunning operations in the background and does not provide a user interface. So, what s

More information

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml Understand applications and their components activity service broadcast receiver content provider intent AndroidManifest.xml Android Application Written in Java (it s possible to write native code) Good

More information

Getting Started. Dr. Miguel A. Labrador Department of Computer Science & Engineering

Getting Started. Dr. Miguel A. Labrador Department of Computer Science & Engineering Getting Started Dr. Miguel A. Labrador Department of Computer Science & Engineering labrador@csee.usf.edu http://www.csee.usf.edu/~labrador 1 Goals Setting up your development environment Android Framework

More information

Android. Mobile operating system developed by Google A complete stack. Based on the Linux kernel Open source under the Apache 2 license

Android. Mobile operating system developed by Google A complete stack. Based on the Linux kernel Open source under the Apache 2 license Android Android Mobile operating system developed by Google A complete stack OS, framework A rich set of applications Email, calendar, browser, maps, text messaging, contacts, camera, dialer, music player,

More information

Android Fundamentals - Part 1

Android Fundamentals - Part 1 Android Fundamentals - Part 1 Alexander Nelson September 1, 2017 University of Arkansas - Department of Computer Science and Computer Engineering Reminders Projects Project 1 due Wednesday, September 13th

More information

Diving into Android. By Jeroen Tietema. Jeroen Tietema,

Diving into Android. By Jeroen Tietema. Jeroen Tietema, Diving into Android By Jeroen Tietema Jeroen Tietema, 2015 1 Requirements 4 Android SDK 1 4 Android Studio (or your IDE / editor of choice) 4 Emulator (Genymotion) or a real device. 1 See https://developer.android.com

More information

Introduction to Android Development

Introduction to Android Development Introduction to Android Development What is Android? Android is the customizable, easy to use operating system that powers more than a billion devices across the globe - from phones and tablets to watches,

More information

Software Practice 3 Before we start Today s lecture Today s Task Team organization

Software Practice 3 Before we start Today s lecture Today s Task Team organization 1 Software Practice 3 Before we start Today s lecture Today s Task Team organization Prof. Hwansoo Han T.A. Jeonghwan Park 43 2 Lecture Schedule Spring 2017 (Monday) This schedule can be changed M A R

More information

Embedded Systems Programming - PA8001

Embedded Systems Programming - PA8001 Embedded Systems Programming - PA8001 http://goo.gl/ydeczu Lecture 8 Mohammad Mousavi m.r.mousavi@hh.se Center for Research on Embedded Systems School of Information Science, Computer and Electrical Engineering

More information

Android Overview. Most of the material in this section comes from

Android Overview. Most of the material in this section comes from Android Overview Most of the material in this section comes from http://developer.android.com/guide/ Android Overview A software stack for mobile devices Developed and managed by Open Handset Alliance

More information

IPN-ESCOM Application Development for Mobile Devices. Extraordinary. A Web service, invoking the SOAP protocol, in an Android application.

IPN-ESCOM Application Development for Mobile Devices. Extraordinary. A Web service, invoking the SOAP protocol, in an Android application. Learning Unit Exam Project IPN-ESCOM Application Development for Mobile Devices. Extraordinary. A Web service, invoking the SOAP protocol, in an Android application. The delivery of this project is essential

More information

Real-Time Embedded Systems

Real-Time Embedded Systems Real-Time Embedded Systems DT8025, Fall 2016 http://goo.gl/azfc9l Lecture 8 Masoumeh Taromirad m.taromirad@hh.se Center for Research on Embedded Systems School of Information Technology 1 / 51 Smart phones

More information

Android Basics. - Bhaumik Shukla Android Application STEALTH FLASH

Android Basics. - Bhaumik Shukla Android Application STEALTH FLASH Android Basics - Bhaumik Shukla Android Application Developer @ STEALTH FLASH Introduction to Android Android is a software stack for mobile devices that includes an operating system, middleware and key

More information

App Development for Android. Prabhaker Matet

App Development for Android. Prabhaker Matet App Development for Android Prabhaker Matet Development Tools (Android) Java Java is the same. But, not all libs are included. Unused: Swing, AWT, SWT, lcdui Android Studio (includes Intellij IDEA) Android

More information

Applications. Marco Ronchetti Università degli Studi di Trento

Applications. Marco Ronchetti Università degli Studi di Trento Applications Marco Ronchetti Università degli Studi di Trento Android Applications An Android application typically consists of one or more related, loosely bound activities for the user to interact with.

More information

Introduction to Android

Introduction to Android Introduction to Android Ambient intelligence Teodoro Montanaro Politecnico di Torino, 2016/2017 Disclaimer This is only a fast introduction: It is not complete (only scrapes the surface) Only superficial

More information

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology Android App Development Mr. Michaud ICE Programs Georgia Institute of Technology Android Operating System Created by Android, Inc. Bought by Google in 2005. First Android Device released in 2008 Based

More information

Mobile OS. Symbian. BlackBerry. ios. Window mobile. Android

Mobile OS. Symbian. BlackBerry. ios. Window mobile. Android Ing. Elton Domnori December 7, 2011 Mobile OS Symbian BlackBerry Window mobile Android ios Mobile OS OS First release Last release Owner Android Android 1.0 September 2008 Android 4.0 May 2011 Open Handset

More information

Vienos veiklos būsena. Theory

Vienos veiklos būsena. Theory Vienos veiklos būsena Theory While application is running, we create new Activities and close old ones, hide the application and open it again and so on, and Activity can process all these events. It is

More information

Android Software Development Kit (Part I)

Android Software Development Kit (Part I) Android Software Development Kit (Part I) Gustavo Alberto Rovelo Ruiz October 29th, 2010 Look & Touch Group 2 Presentation index What is Android? Android History Stats Why Andriod? Android Architecture

More information

Introduction to Android

Introduction to Android Introduction to Android Ambient intelligence Alberto Monge Roffarello Politecnico di Torino, 2017/2018 Some slides and figures are taken from the Mobile Application Development (MAD) course Disclaimer

More information

ECOM 5341 Mobile Computing(Android) Eng.Ruba A. Salamah

ECOM 5341 Mobile Computing(Android) Eng.Ruba A. Salamah ECOM 5341 Mobile Computing(Android) 1 Eng.Ruba A. Salamah Lecture # 2 Android Tools Objectives Understand Android Tools Setup Android Development Environment Create HelloWorld Application Understand HelloWorld

More information

Mobile Application Development - Android

Mobile Application Development - Android Mobile Application Development - Android MTAT.03.262 Satish Srirama satish.srirama@ut.ee Goal Give you an idea of how to start developing Android applications Introduce major Android application concepts

More information

Android Beginners Workshop

Android Beginners Workshop Android Beginners Workshop at the M O B IL E M O N D AY m 2 d 2 D E V E L O P E R D A Y February, 23 th 2010 Sven Woltmann, AndroidPIT Sven Woltmann Studied Computer Science at the TU Ilmenau, 1994-1999

More information

Getting started: Installing IDE and SDK. Marco Ronchetti Università degli Studi di Trento

Getting started: Installing IDE and SDK. Marco Ronchetti Università degli Studi di Trento Getting started: Installing IDE and SDK Marco Ronchetti Università degli Studi di Trento Alternative: Android Studio http://developer.android.com/develop/index.html 2 Tools behind the scenes dx allows

More information

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I) ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I) Lecture 3: Android Life Cycle and Permission Android Lifecycle An activity begins its lifecycle when entering the oncreate() state If not

More information

Introduction to Android

Introduction to Android Introduction to Android http://myphonedeals.co.uk/blog/33-the-smartphone-os-complete-comparison-chart www.techradar.com/news/phone-and-communications/mobile-phones/ios7-vs-android-jelly-bean-vs-windows-phone-8-vs-bb10-1159893

More information

Security model. Marco Ronchetti Università degli Studi di Trento

Security model. Marco Ronchetti Università degli Studi di Trento Security model Marco Ronchetti Università degli Studi di Trento Security model 2 Android OS is a multi-user Linux in which each application is a different user. By default, the system assigns each application

More information

LECTURE NOTES OF APPLICATION ACTIVITIES

LECTURE NOTES OF APPLICATION ACTIVITIES Department of Information Networks The University of Babylon LECTURE NOTES OF APPLICATION ACTIVITIES By College of Information Technology, University of Babylon, Iraq Samaher@inet.uobabylon.edu.iq The

More information

Android Services. Victor Matos Cleveland State University. Services

Android Services. Victor Matos Cleveland State University. Services 22 Android Victor Matos Cleveland State University Notes are based on: Android Developers http://developer.android.com/index.html 22. Android Android A Service is an application component that runs in

More information

Lab 1: Getting Started With Android Programming

Lab 1: Getting Started With Android Programming Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Eng. Jehad Aldahdooh Mobile Computing Android Lab Lab 1: Getting Started With Android Programming To create a new Android Project

More information

COMP4521 EMBEDDED SYSTEMS SOFTWARE

COMP4521 EMBEDDED SYSTEMS SOFTWARE COMP4521 EMBEDDED SYSTEMS SOFTWARE LAB 1: DEVELOPING SIMPLE APPLICATIONS FOR ANDROID INTRODUCTION Android is a mobile platform/os that uses a modified version of the Linux kernel. It was initially developed

More information

EMBEDDED SYSTEMS PROGRAMMING Application Basics

EMBEDDED SYSTEMS PROGRAMMING Application Basics EMBEDDED SYSTEMS PROGRAMMING 2015-16 Application Basics APPLICATIONS Application components (e.g., UI elements) are objects instantiated from the platform s frameworks Applications are event driven ( there

More information

Lecture 2 Android SDK

Lecture 2 Android SDK Lecture 2 Android SDK This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/ or send a

More information

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I) ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I) Lecture 3: Android Life Cycle and Permission Entire Lifetime An activity begins its lifecycle when entering the oncreate() state If not interrupted

More information

Android Apps Development for Mobile and Tablet Device (Level I) Lesson 2

Android Apps Development for Mobile and Tablet Device (Level I) Lesson 2 Workshop 1. Compare different layout by using Change Layout button (Page 1 5) Relative Layout Linear Layout (Horizontal) Linear Layout (Vertical) Frame Layout 2. Revision on basic programming skill - control

More information

LifeStreet Media Android Publisher SDK Integration Guide

LifeStreet Media Android Publisher SDK Integration Guide LifeStreet Media Android Publisher SDK Integration Guide Version 1.12.0 Copyright 2015 Lifestreet Corporation Contents Introduction... 3 Downloading the SDK... 3 Choose type of SDK... 3 Adding the LSM

More information

Services. Marco Ronchetti Università degli Studi di Trento

Services. Marco Ronchetti Università degli Studi di Trento 1 Services Marco Ronchetti Università degli Studi di Trento Service An application component that can perform longrunning operations in the background and does not provide a user interface. So, what s

More information

Solving an Android Threading Problem

Solving an Android Threading Problem Home Java News Brief Archive OCI Educational Services Solving an Android Threading Problem Introduction by Eric M. Burke, Principal Software Engineer Object Computing, Inc. (OCI) By now, you probably know

More information

BCA 6. Question Bank

BCA 6. Question Bank BCA 6 030010601 : Introduction to Mobile Application Development Question Bank Unit 1: Introduction to Android and Development tools Short questions 1. What kind of tool is used to simulate Android application?

More information

Android. Broadcasts Services Notifications

Android. Broadcasts Services Notifications Android Broadcasts Services Notifications Broadcast receivers Application components that can receive intents from other applications Broadcast receivers must be declared in the manifest They have an associated

More information

Java & Android. Java Fundamentals. Madis Pink 2016 Tartu

Java & Android. Java Fundamentals. Madis Pink 2016 Tartu Java & Android Java Fundamentals Madis Pink 2016 Tartu 1 Agenda» Brief background intro to Android» Android app basics:» Activities & Intents» Resources» GUI» Tools 2 Android» A Linux-based Operating System»

More information

Programming Concepts and Skills. Creating an Android Project

Programming Concepts and Skills. Creating an Android Project Programming Concepts and Skills Creating an Android Project Getting Started An Android project contains all the files that comprise the source code for your Android app. The Android SDK tools make it easy

More information

Android Workshop: Model View Controller ( MVC):

Android Workshop: Model View Controller ( MVC): Android Workshop: Android Details: Android is framework that provides java programmers the ability to control different aspects of smart devices. This interaction happens through the Android SDK (Software

More information

CS 403X Mobile and Ubiquitous Computing Lecture 3: Introduction to Android Programming Emmanuel Agu

CS 403X Mobile and Ubiquitous Computing Lecture 3: Introduction to Android Programming Emmanuel Agu CS 403X Mobile and Ubiquitous Computing Lecture 3: Introduction to Android Programming Emmanuel Agu Android UI Tour Home Screen First screen, includes favorites tray (e.g phone, mail, messaging, web, etc)

More information

TPCT s College of Engineering, Osmanabad. Laboratory Manual SDL-II. Mobile Application Development (Android) For. Third Year Students (CSE)

TPCT s College of Engineering, Osmanabad. Laboratory Manual SDL-II. Mobile Application Development (Android) For. Third Year Students (CSE) TPCT s College of Engineering, Osmanabad Laboratory Manual SDL-II Mobile Application Development (Android) For Third Year Students (CSE) Manual Prepared by Prof. Sujata A. Gaikwad Author COE, Osmanabad

More information

COPYRIGHTED MATERIAL. 1Getting Started with Android Programming

COPYRIGHTED MATERIAL. 1Getting Started with Android Programming 1Getting Started with Android Programming WHAT YOU WILL LEARN IN THIS CHAPTER What is Android? Android versions and its feature set The Android architecture The various Android devices on the market The

More information

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology Mobile Application Development Produced by David Drohan (ddrohan@wit.ie) Department of Computing & Mathematics Waterford Institute of Technology http://www.wit.ie Android Anatomy Android Anatomy 2! Agenda

More information

Mobile Computing. Introduction to Android

Mobile Computing. Introduction to Android Mobile Computing Introduction to Android Mobile Computing 2011/2012 What is Android? Open-source software stack for mobile devices OS, middleware and key applications Based upon a modified version of the

More information

Our First Android Application

Our First Android Application Mobile Application Development Lecture 04 Imran Ihsan Our First Android Application Even though the HelloWorld program is trivial in introduces a wealth of new ideas the framework, activities, manifest,

More information

Android for Ubiquitous Computing Researchers. Andrew Rice University of Cambridge 17-Sep-2011

Android for Ubiquitous Computing Researchers. Andrew Rice University of Cambridge 17-Sep-2011 Android for Ubiquitous Computing Researchers Andrew Rice University of Cambridge 17-Sep-2011 Getting started Website for the tutorial: http://www.cl.cam.ac.uk/~acr31/ubicomp/ Contains links to downloads

More information

Services. Background operating component without a visual interface Running in the background indefinitely

Services. Background operating component without a visual interface Running in the background indefinitely Services Background operating component without a visual interface Running in the background indefinitely Differently from Activity, Service in Android runs in background, they don t have an interface

More information

Android Exam AND-401 Android Application Development Version: 7.0 [ Total Questions: 129 ]

Android Exam AND-401 Android Application Development Version: 7.0 [ Total Questions: 129 ] s@lm@n Android Exam AND-401 Android Application Development Version: 7.0 [ Total Questions: 129 ] Android AND-401 : Practice Test Question No : 1 Which of the following is required to allow the Android

More information

CS378 -Mobile Computing. Services and Broadcast Receivers

CS378 -Mobile Computing. Services and Broadcast Receivers CS378 -Mobile Computing Services and Broadcast Receivers Services One of the four primary application components: activities content providers services broadcast receivers 2 Services Application component

More information

MAD ASSIGNMENT NO 2. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept.

MAD ASSIGNMENT NO 2. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept. MAD ASSIGNMENT NO 2 Submitted by: Rehan Asghar BSSE 7 15126 AUGUST 25, 2017 SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept. Android Widgets There are given a lot of android widgets with simplified

More information

Android App Development. Muhammad Sharjeel COMSATS Institute of Information Technology, Lahore

Android App Development. Muhammad Sharjeel COMSATS Institute of Information Technology, Lahore Android App Development Muhammad Sharjeel COMSATS Institute of Information Technology, Lahore Mobile devices (e.g., smartphone, tablet PCs, etc.) are increasingly becoming an essential part of human life

More information

Android App Development. Ahmad Tayeb

Android App Development. Ahmad Tayeb Android App Development Ahmad Tayeb Ahmad Tayeb Lecturer @ Department of Information Technology, Faculty of Computing and Information Technology, KAU Master degree from Information Sciences and Technologies,

More information

COLLEGE OF ENGINEERING, NASHIK-4

COLLEGE OF ENGINEERING, NASHIK-4 Pune Vidyarthi Griha s COLLEGE OF ENGINEERING, NASHIK-4 DEPARTMENT OF COMPUTER ENGINEERING 1) What is Android? Important Android Questions It is an open-sourced operating system that is used primarily

More information

Required Core Java for Android application development

Required Core Java for Android application development Required Core Java for Android application development Introduction to Java Datatypes primitive data types non-primitive data types Variable declaration Operators Control flow statements Arrays and Enhanced

More information

Xin Pan. CSCI Fall

Xin Pan. CSCI Fall Xin Pan CSCI5448 2011 Fall Outline Introduction of Android System Four primary application components AndroidManifest.xml Introduction of Android Sensor Framework Package Interface Classes Examples of

More information

Fig. 2.2 New Android Application dialog. 2.3 Creating an App 41

Fig. 2.2 New Android Application dialog. 2.3 Creating an App 41 AndroidHTP_02.fm Page 41 Wednesday, April 30, 2014 3:00 PM 2.3 Creating an App 41 the Welcome app s TextView and the ImageViews accessibility strings, then shows how to test the app on an AVD configured

More information

CS 4518 Mobile and Ubiquitous Computing Lecture 2: Introduction to Android. Emmanuel Agu

CS 4518 Mobile and Ubiquitous Computing Lecture 2: Introduction to Android. Emmanuel Agu CS 4518 Mobile and Ubiquitous Computing Lecture 2: Introduction to Android Emmanuel Agu What is Android? Android is world s leading mobile operating system Open source Google: Owns Android, maintains it,

More information

Android Basics. Android UI Architecture. Android UI 1

Android Basics. Android UI Architecture. Android UI 1 Android Basics Android UI Architecture Android UI 1 Android Design Constraints Limited resources like memory, processing, battery à Android stops your app when not in use Primarily touch interaction à

More information

LECTURE NOTES ON MOBILE APPLICATION DEVELOPMENT

LECTURE NOTES ON MOBILE APPLICATION DEVELOPMENT LECTURE NOTES ON MOBILE APPLICATION DEVELOPMENT 2018 2019 IV B. Tech I Semester (JNTUA-R15) Ms. A.Ragini, Assistant Professor CHADALAWADA RAMANAMMA ENGINEERING COLLEGE (AUTONOMOUS) Chadalawada Nagar, Renigunta

More information

Mobile Programming Practice Background processing AsynTask Service Broadcast receiver Lab #5

Mobile Programming Practice Background processing AsynTask Service Broadcast receiver Lab #5 1 Mobile Programming Practice Background processing AsynTask Service Broadcast receiver Lab #5 Prof. Hwansoo Han T.A. Sung-in Hong T.A. Minseop Jeong 2 Background processing Every Android app has a main

More information

Android UI Development

Android UI Development Android UI Development Android UI Studio Widget Layout Android UI 1 Building Applications A typical application will include: Activities - MainActivity as your entry point - Possibly other activities (corresponding

More information

Embedded Systems Programming - PA8001

Embedded Systems Programming - PA8001 Embedded Systems Programming - PA8001 http://goo.gl/ydeczu Lecture 9 Mohammad Mousavi m.r.mousavi@hh.se Center for Research on Embedded Systems School of Information Science, Computer and Electrical Engineering

More information

Computer Science E-76 Building Mobile Applications

Computer Science E-76 Building Mobile Applications Computer Science E-76 Building Mobile Applications Lecture 3: [Android] The SDK, Activities, and Views February 13, 2012 Dan Armendariz danallan@mit.edu 1 http://developer.android.com Android SDK and NDK

More information

COSC 3P97 Mobile Computing

COSC 3P97 Mobile Computing COSC 3P97 Mobile Computing Mobile Computing 1.1 COSC 3P97 Prerequisites COSC 2P13, 3P32 Staff instructor: Me! teaching assistant: Steve Tkachuk Lectures (MCD205) Web COSC: http://www.cosc.brocku.ca/ COSC

More information

Android App Development

Android App Development Android App Development Outline Introduction Android Fundamentals Android Studio Tutorials Introduction What is Android? A software platform and operating system for mobile devices Based on the Linux kernel

More information

CS 234/334 Lab 1: Android Jump Start

CS 234/334 Lab 1: Android Jump Start CS 234/334 Lab 1: Android Jump Start Distributed: January 7, 2014 Due: Friday, January 10 or Monday, January 13 (in-person check off in Mobile Lab, Ry 167). No late assignments. Introduction The goal of

More information

SHWETANK KUMAR GUPTA Only For Education Purpose

SHWETANK KUMAR GUPTA Only For Education Purpose Introduction Android: INTERVIEW QUESTION AND ANSWER Android is an operating system for mobile devices that includes middleware and key applications, and uses a modified version of the Linux kernel. It

More information

CS378 -Mobile Computing. Anatomy of and Android App and the App Lifecycle

CS378 -Mobile Computing. Anatomy of and Android App and the App Lifecycle CS378 -Mobile Computing Anatomy of and Android App and the App Lifecycle Hello Android Tutorial http://developer.android.com/resources/tutorials/hello-world.html Important Files src/helloandroid.java Activity

More information

GUI Design for Android Apps, Part 1: General Overview

GUI Design for Android Apps, Part 1: General Overview Chapter 7 GUI Design for Android Apps, Part 1: General Overview Since its emergence in the 1980s, the concept of the graphical user interface (GUI) has become an indispensable part of human-computer interaction

More information

Android Programming in Bluetooth Cochlea Group

Android Programming in Bluetooth Cochlea Group Android Programming in Bluetooth Cochlea Group Zijian Zhao Abstract: My project is mainly android programming work in the Bluetooth Cochlea Group. In this report I will first introduce the background of

More information

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi ACTIVITY, FRAGMENT, NAVIGATION Roberto Beraldi Introduction An application is composed of at least one Activity GUI It is a software component that stays behind a GUI (screen) Activity It runs inside the

More information

Configuring the Android Manifest File

Configuring the Android Manifest File Configuring the Android Manifest File Author : userone What You ll Learn in This Hour:. Exploring the Android manifest file. Configuring basic application settings. Defining activities. Managing application

More information

CS 528 Mobile and Ubiquitous Computing Lecture 1b: Introduction to Android. Emmanuel Agu

CS 528 Mobile and Ubiquitous Computing Lecture 1b: Introduction to Android. Emmanuel Agu CS 528 Mobile and Ubiquitous Computing Lecture 1b: Introduction to Android Emmanuel Agu What is Android? Android is world s leading mobile operating system Open source (https://source.android.com/setup/)

More information

An Overview of the Android Programming

An Overview of the Android Programming ID2212 Network Programming with Java Lecture 14 An Overview of the Android Programming Hooman Peiro Sajjad KTH/ICT/SCS HT 2016 References http://developer.android.com/training/index.html Developing Android

More information

M O B I L E T R A I N I N G. Beginning Your Android Programming Journey

M O B I L E T R A I N I N G. Beginning Your Android Programming Journey Beginning Your Android Programming Journey An Introductory Chapter from EDUmobile.ORG Android Development Training Program NOTICE: You Do NOT Have the Right to Reprint or Resell This ebook! You Also MAY

More information

8/30/15 MOBILE COMPUTING. CSE 40814/60814 Fall How many of you. have implemented a command-line user interface?

8/30/15 MOBILE COMPUTING. CSE 40814/60814 Fall How many of you. have implemented a command-line user interface? MOBILE COMPUTING CSE 40814/60814 Fall 2015 How many of you have implemented a command-line user interface? 1 How many of you have implemented a graphical user interface? HTML/CSS Java Swing.NET Framework

More information

CS 528 Mobile and Ubiquitous Computing Lecture 3: Android UI, WebView, Android Activity Lifecycle Emmanuel Agu

CS 528 Mobile and Ubiquitous Computing Lecture 3: Android UI, WebView, Android Activity Lifecycle Emmanuel Agu CS 528 Mobile and Ubiquitous Computing Lecture 3: Android UI, WebView, Android Activity Lifecycle Emmanuel Agu Android UI Design Example GeoQuiz App Reference: Android Nerd Ranch, pgs 1 30 App presents

More information

Building MyFirstApp Android Application Step by Step. Sang Shin Learn with Passion!

Building MyFirstApp Android Application Step by Step. Sang Shin   Learn with Passion! Building MyFirstApp Android Application Step by Step. Sang Shin www.javapassion.com Learn with Passion! 1 Disclaimer Portions of this presentation are modifications based on work created and shared by

More information

Produced by. Mobile Application Development. Eamonn de Leastar

Produced by. Mobile Application Development. Eamonn de Leastar Mobile Application Development Produced by Eamonn de Leastar (edeleastar@wit.ie) Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie A First

More information

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L 2 0 1 5 Activity Basics Manifest File AndroidManifest.xml Central configuration of Android application Defines: Name of application Icon for

More information

Android Programming (5 Days)

Android Programming (5 Days) www.peaklearningllc.com Android Programming (5 Days) Course Description Android is an open source platform for mobile computing. Applications are developed using familiar Java and Eclipse tools. This Android

More information