AndroidLabManualforNoviceVolI
AndroidLabManualforNoviceVolI
ii
Android Lab Manual for Novice – Vol I
By
iii
Android Lab Manual for Novice
Acknowledgements
Many individuals share credit for this book’s preparation. We extend our sincere thanks to Late Prof.
A.D.Shinde, the Founder Director and Managing Trustee who has been a constant source of inspiration
for us throughout our career. His support is really a driving force for us. Also, we would like to thank
Dr.R.A.Shinde, Hon’ble Secretary, CSIBER, Kolhapur for his whole hearted support and continuous
encouragement. We are grateful to Dr. M.M.Ali, Director CSIBER, Kolhapur for his invaluable guidance.
We take this opportunity to thank Dr.V.M.Hilage, Former Director and Trustee Member, CSIBER,
Kolhapur, Mr. Bharat Patil, Chairman, Mr. Sunil Kulkarni, Vice Chairman, and Deepak Chougule,
Secretary, KIT, Kolhapur, Dr. R.V.Kulkarni, H.O.D., Department of Computer Studies, CSIBER,
Kolhapur for showing a keen interest in the matter of this book and extending all support facilities for the
in-timely completion of this book. Last but not the least we thank all faculty members and non-teaching
staff of department of computer studies, CSIBER, Kolhapur and Production Engineering department,
KIT’s College of Engineering, Kolhapur who have made contribution to this book either directly or
indirectly.
i
Android Lab Manual for Novice
Preface
It gives us an immense pleasure to bring out a book entitled ‘Android Lab Manual for Novice – Vol I’.
In this era of globalization, mobile apps have revolutionized the way the business is conducted.
To cater the needs of customers, IT companies are investing tremendously in app development
which has opened new employability opportunities for computer professionals. Currently
Android is the most popular mobile platform available in the market having more than 85% of
market share. Android operating system is dominating the mobile platform market. Android is an
exciting and evolving technology Google keeps on updating the Android operating system with
new features and enhanced security which is the need of an hour. Since Android is open source it
requires comparatively lesser investment and tremendously reduces development cost. The entire
Android platform is ready for customization which makes simple complex technical
customization The remarkable feature of Android is the minimum time to market which provides
an upper hand and a competitive edge over the rivals. As new android enabled devices are
popping up, the new avenues are opened for Android developers and there is very high demand
for Android developers. With hundreds of millions of users around the world, the possibilities for
gainful employment seem endless. The basic skill sets demand an extensive exposure to Android
IDE and SDK. This book is exactly meant for that which unleashes most of the concepts hidden
behind the set of APIs and brings them infront of the reader. This book is intended for a novice
who is keen in getting first-hand information about Android. The basic skill required for
improving employability opportunities in this area include understanding of layouts and views,
exposure to basic components of Android, android resources, data persistence, to name a few.
The only pre-requisite for understanding the content of this book is the basic knowledge of java
language. The book is thought provoking which motivates the reader to think out of the box and
explore new features available in the application framework.
Chapter 1 focuses on basic features and architecture of Android and provides insight into
execution of Android application. The main feature of the chapter is setting up development environment
which focuses on setting up ADT bundled eclipse and Android Studio. Android application folder
ii
Android Lab Manual for Novice
structure is explored at depth. Downloading Android platforms and creating AVD for testing Android
applications are also discussed. Chapter concludes with discussion of command-line tools, Android
Debug Bridge (ADB), Activity Manager and Package Manager. Chapter 2 is devoted for basic building
blocks of Android, core Android libraries and different types of layouts understanding of which is crucial
for developing working application in Android. Anatomy of Android application is presented. The
structure of R class and basic elements of AndroidManifest.xml file where the prime system configuration
information resides are also discussed. The main highlight of the chapter is more than one ways of
handling events in Android with are discussed along with suitable examples in each case. Chapter 3
explores different types of resources available in Android. Basic steps involved in creating and using
string resource, string array resource, style resource and menu resource both in eclipse and Android
Studio are discussed. Finally Chapter 4 provides an overview of various pre-defined dialogs available in
Android such as AlertDialog, DatePickerDialog, TimePickerDialog, ProgressDialog and
CharacerPickerDialog which aid in rapid application development and help in rendering the application
user friendly.
The content of this book is derived from different sources which are listed at the end in a
‘references’ section.
iii
Android Lab Manual for Novice
Contents
iv
Android Lab Manual for Novice
v
Android Lab Manual for Novice
vi
Android Lab Manual for Novice
CHAPTER 1
Setting Up Android Development Environment
1.1 Introduction of Android
Android is a complete software stack for mobile devices which contains a linux-based
Operating System, middleware and key mobile applications. It can be thought of as a mobile
operating system. But it is not limited to smart phones only. It is currently used in various
devices such as mobiles, tablets, televisions, electronic book readers, set-top boxes, etc.
It is an open source platform which abstracts out the hardware from the software that runs
on it thereby enabling the large number of devices to run the same application. Android does not
make any assumption on device attributes such as screen size, resolution etc. which enhances its
portability to numerous devices.
Android is developed initially by Google and later by OHA (Open Handset Alliance).
Java language is mainly used to write the android code even though other languages can be used.
The goal of android project is to create a successful real-world product that improves the mobile
experience for end users.
1
Android Lab Manual for Novice
It provides many interesting features like weather details, opening screen, live RSS
(Really Simple Syndication) feeds etc.
It provides support for messaging services(SMS and MMS), web browser, storage
(SQLite), connectivity (GSM, CDMA, Blue Tooth, Wi-Fi etc.), media, handset layout
etc.
2
Android Lab Manual for Novice
Linux kernel
It is the heart of android architecture that exists at the root of android architecture. Linux kernel
is responsible for device drivers, power management, memory management, device management
and resource access.
Native Libraries
On the top of linux kernel, there are Native libraries such as WebKit, OpenGL, FreeType,
SQLite, Media, C runtime library (libc) etc.
The WebKit library is responsible for browser support, SQLite is for database, FreeType for font
support, Media for playing and recording audio and video formats.
3
Android Lab Manual for Novice
Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is
responsible to run android application. DVM is like JVM but it is optimized for mobile devices.
It consumes less memory and provides fast performance.
Android Framework
On the top of Native libraries and android runtime, there is android framework. Android
framework includes Android API's such as UI (User Interface), telephony, resources, locations,
Content Providers (data) and package managers. It provides a lot of classes and interfaces for
android application development.
Applications
On the top of android framework, there are applications. All applications such as home, contact,
settings, games, browsers are using android framework that uses android runtime and libraries.
Android runtime and native libraries are using linux kernel.
The following table depicts the code names, versions and API level for different Android
releases.
4
Android Lab Manual for Novice
5
Android Lab Manual for Novice
The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile
devices. It optimizes the virtual machine for memory, battery life and performance.
Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.
The Dex compiler converts the class files into the .dex file that run on the Dalvik VM.
Multiple class files are converted into one dex file.
The following figure shows the compiling and packaging process of Android application from
java source files:
6
Android Lab Manual for Novice
Android studio includes Android SDK and an installer which will install all the required
components with a single click.
If you download the Android Studio from android site, you don't need to have eclipse IDE,
android SDK and eclipse Plugin because it is already included in Android Studio.
If you have downloaded the ADT Bundled Eclipse, unjar it, go to eclipse IDE and start the
eclipse by clicking on the eclipse icon. You don't need to do any extra steps here.
7
Android Lab Manual for Novice
8
Android Lab Manual for Novice
ADT Plug-in
The ADT plug-in adds Android-specific functionality to Eclipse. Software in the plug-in enables
Eclipse to build Android applications, launch the Android emulator, connect to debugging
services on the emulator, edit Android XML files, edit and compile Android Interface Definition
Language (AIDL) files, create Android application packages (.apk files), and perform other
Android-specific tasks.
ADT (Android Development Tools) is required for developing the android application in the
eclipse IDE. It is the plugin for Eclipse IDE that is designed to provide the integrated
environment.
9
Android Lab Manual for Novice
2. Select “Available Software” tab and click on “Add Site” button and enter the location
given below:
https://dl-ssl.google.com/android/eclipse/
3. Select the checkbox next to ‘Developer Tools’ and click on ‘Next’ button
4. List of tools to be downloaded here is displayed, click on ‘Next’ button
5. Click on ‘Finish’ button.
6. After completing the installation, restart the eclipse IDE.
10
Android Lab Manual for Novice
The Android SDK provides an emulator, which emulates a device with an ARM CPU running an
Android operating system (OS), for running Android programs on your PC. An Android Virtual
Device (AVD) is a set of parameters for this emulator that configures it to use a particular system
image—that is, a particular version of the Android operating system—and to set other
parameters that govern screen size, memory size, and other emulated hardware characteristics.
Android Emulator is used to run, debug and test the android application. If you don't have the
real device, it can be the best way to run, debug and test the application. It uses an open source
11
Android Lab Manual for Novice
processor emulator technology called ‘QEMU’. The ‘emulator’ tool enables you to start the
emulator from the command line.
For running the android application in the Android Emulator, you need to create an AVD. For
creating the AVD follow the steps given below:
1. Select the menu option Window → Android Virtual Device Manager from the main
menu.
2. Click on the ‘New’ button to create the AVD
3. ‘Create New Android Virtual Device (AVD)’ dialog appears, enter the AVD name e.g.
‘siber’. Now choose the Target Android Version, for Example, Android 4.2 and other
configuration details such as skin, memory, internal storage size, SD card size etc.
4. Finally, click on “OK” button to create AVD.
12
Android Lab Manual for Novice
13
Android Lab Manual for Novice
You will need to create an AVD with a system image that is no less recent than the target
specified for the project you created. Click the New button. You will now see the “Create new
Android Virtual Device (AVD)” dialog, shown in the above figure, where you specify the
parameters of your new AVD.
This screen enables you to set the parameters of your new AVD:
Name
This is the name of the AVD. You can use any name for an AVD, but a name that
indicates which system image it uses is helpful.
Target
The Target parameter sets which system image will be used in this AVD. It should be the
same as, or more recent than, the target you selected as the build target for your first
Android project.
SD Card
Some applications require an SD card that extends storage beyond the flash memory built
into an Android device. Unless you plan to put a lot of data in SD card storage (media
files, for example) for applications you are developing, you can create a small virtual SD
card of, say, 100 MB in size, even though most phones are equipped with SD cards
holding several gigabytes.
Skin
The “skin” of an AVD mainly sets the screen size. You won’t need to change the default
for the purpose of verifying that your SDK installation works, but a variety of emulators
14
Android Lab Manual for Novice
with different screen sizes is useful to check that your layouts work across different
devices.
Hardware
The Hardware field of an AVD configuration enables you to set parameters indicating
which optional hardware is present. You won’t need to change the defaults for this
project.
Fill in the Name, Target, and SD Card fields, and create a new AVD by clicking the Create AVD
button. If you have not created an AVD with a system image that matches or is more recent than
the target you specified for an Android project, you won’t be able to run your program.
Now that you have a project that builds an application, and an AVD with a system image
compatible with the application’s build target and API level requirements, you can run your
application and confirm that the SDK produced and is able to run an Android application.
You can also run the program you just created on most Android devices.
You will need to connect your device to your PC with a USB cable, and, if needed, install a
driver, or set permissions to access the device when connected via USB.
If you are running Linux, you will need to create a “rules” file for your Android device.
You will also need to turn on USB debugging in your Android device. In most cases, you will
start the Settings application, select Applications and then Development, and then see an option
to turn USB debugging on or off.
If an AVD is configured or is running, the Android Device Chooser will appear, displaying both
the Android device you have connected and the AVD.
15
Android Lab Manual for Novice
Select the device, and the Android application will be loaded and run on the device.
For every AVD file, there is a corresponding ‘.ini’ file storing the important configuration
information about the AVD. For example for ‘MCA.avd’ file the corresponding configuration
file is ‘MAC.ini’ which contains the following information:
16
Android Lab Manual for Novice
The ‘MCA.avd’ folder contains the disk images files for SD card, configuration information etc.
17
Android Lab Manual for Novice
If you are unable to make a new project or import an example project from the SDK, you may
have missed installing build targets into your SDK.
2. Select the AVD you want to launch and click on ‘start’ button as shown in the following
figure
3. ‘Launch Options’ dialog appears as shown in the following figure, click on ‘Launch’
button.
18
Android Lab Manual for Novice
The following figure depicts launching emulator. Despite the warning messages displayed,
emulator will launch successfully.
19
Android Lab Manual for Novice
20
Android Lab Manual for Novice
2. Click on the ‘Advanced’ tab and click on ‘Environment Variables…’ button as shown in
the following figure:
21
Android Lab Manual for Novice
3. Create a new environment variable with the name ‘ANDROID_HOME’ with the value
‘D:\android\adt-bundle-windows-x86-20130522\adt-bundle-windows-x86-20130522\sdk’
pointing to the Android SDK location as shown in the following figure:
22
Android Lab Manual for Novice
4. Create a new environment variable with the name ‘ANDROID_SDK_ROOT’ with the
value ‘D:\android\adt-bundle-windows-x86-20130522\adt-bundle-windows-x86-20130522\sdk’
pointing to the Android SDK location as shown in the following figure:
23
Android Lab Manual for Novice
Package Explorer
It displays a hierarchical view of different files and folders in an Android project
LogCat Windows
It displays different messages written to the log file. The windows contains options for creating
logical group of messages and the messages can be filtered according to the group to view only
the messages in a specific group.
Outline Windows
It displays component tree for the selected layout.
24
Android Lab Manual for Novice
Double-click on the folder to open it. The folder contains the following items. The SDK folder
contains the tools for application development and ‘eclipse’ folder contains an executable to
launch Eclipse IDE.
25
Android Lab Manual for Novice
Browse and select the required workspace. All the Android projects will be created in the
selected workspace. In the current example, all the project folders will reside inside a workspace
folder ‘F:\pgn’.
Select File → New Android Application Project from the main menu as shown below:
26
Android Lab Manual for Novice
To create your Android project, you will have to provide the following information:
Project name
This is the name of the project (not the application) that appears in Eclipse. Type
‘HelloAndroid’, as shown in the following figure.
Workspace
27
Android Lab Manual for Novice
Target name
The Android system images you installed in the SDK are shown in the build target list.
You can pick one of these system images, and the corresponding vendor, platform
(Android OS version number), and API level as the target for which your application is
built. The platform and API level are the most important parameters here: they govern the
Android platform library that your application will be compiled with, and the API level
supported—APIs with a higher API level than the one you select will not be available to
your program. For now, pick the most recent Android OS version and API level you have
installed. In the current example, the target SDK is Android 4.2 (API level 17).
Application name
This is the application name the user will see. By default the application name is the same
as project name.
Package name
The package name creates a Java package namespace that uniquely identifies packages in
your application, and must also uniquely identify your whole Android application among
all other installed applications. It consists of a unique domain name—the application
publisher’s domain name—plus a name specific to the application. Not all package
namespaces are unique in Java, but the conventions used for Android applications make
namespace conflicts less likely. In the current example the package name is
‘com.example.helloandroid’, since example.com is a domain name reserved for
examples such as this one.
The field labeled Min SDK Version should contain an integer corresponding to the
minimum SDK version required by your application, and is used to initialize the uses-sdk
attribute in the application’s manifest, which is a file that stores application attributes.
28
Android Lab Manual for Novice
See The Android Manifest Editor. In most cases, this should be the same as the API level
of the build target you selected, which is displayed in the rightmost column of the list of
build targets. . In the current example, the minimum SDK is Android 2.2 (API level 8).
Minimum Required SDK is set to API 8. Lower API levels target more devices but will have
limited features.
Click ‘Next’ two times and then select a blank activity as shown below:
29
Android Lab Manual for Novice
The folder with the name ‘helloandroid’ is created in the folder ‘F:\pgn’ as shown in the
following figure:
30
Android Lab Manual for Novice
Double-click on the folder to view its contents. The project folder contains the following folders
and files.
31
Android Lab Manual for Novice
where, <project_name> is the name of the project specified at the time of creation. In the current
example, the package name is,
com.example.helloandroid
Since in java, a package hierarchy corresponds to a folder hierarchy, the auto-generated class
R.java is located in the folder,
F:\pgn\helloandroid\gen\com\example\helloandroid
F:\pgn\helloandroid\src\com\example\helloandroid
‘res’ folder contains different subfolders for different types of resources as shown in the
following figure:
32
Android Lab Manual for Novice
33
Android Lab Manual for Novice
Android Emulator
Android Emulator is used to run, debug and test the android application.
If more than one emulator is present, the following dialog for selecting the emulator is displayed.
34
Android Lab Manual for Novice
The console window displays the progress of deployment as shown in the following figure:
35
Android Lab Manual for Novice
36
Android Lab Manual for Novice
The following table summarizes the contents of different folders present in a project folder:
37
Android Lab Manual for Novice
Following table lists the tags which can be used in manifest file to specify different Android
application components –
The first and important file created by eclipse IDE is ‘MainActivity.java’ containing definition
of MainActivity class. It is located in ‘src’ folder under ‘com.xample’helloandroid’ folder of
project folder in package explorer.
MainActivity.java
package com.example.first_project;
import android.os.Bundle;
38
Android Lab Manual for Novice
import android.app.Activity;
import android.view.Menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
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;
}
}
Activity is a java class that creates a default window on the screen where we can place different
components such as Button, EditText, TextView, Spinner etc. It is like the Frame of Java AWT.
It provides life cycle methods for activity such as onCreate, onStop, OnResume etc.
The onCreate method is called when Activity class is first created.
The setContentView(R.layout.activity_main) gives information about our layout
resource. Here, our layout resources are defined in activity_main.xml file.
The next important file generated by eclipse IDE is layout resource file with the name
‘activity_main.xml’ located in ‘res/layout’ folder under project folder in a package explorer.
39
Android Lab Manual for Novice
‘activity_main.xml’ is a layout XML file storing information about the container and the
controls present on the container. The root element of ‘activity_main.xml’ file is
<RelativeLayout> and the layout contains a single TextView control whose XML property
‘android:text’ is set to "@string/hello_world” which refers to the string resource with the name
‘hello_world’ present in ‘strings.xml’ file. The structure of ‘activity_main.xml’ file is shown
below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/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>
Note: A textview is created by the framework automatically. The message for this string is
defined in the ‘strings.xml’ file. The ‘@string/hello_world’ provides information about the
textview message. The value of the attribute ‘hello_world’ is defined in the ‘strings.xml’ file.
40
Android Lab Manual for Novice
strings.xml
It is an XML file containing definition of string resources. The root node of the XML file is
<resources> which contains one or more child <string> elements. The name of the string
resource is defined in ‘name’ attribute of the <string> element and the content represents the
value of the string resource. The structure of ‘strings.xml’ file is shown below:
You can change the value of the hello_world attribute from this file.
main.xml
This file contains the menu layout information for the main menu of the application. It contains a
single item with the title defined by a string resource with the name ‘action_settings’ present in
‘strings.xml’ file. The structure of ‘main.xml’ file is shown below:
AndroidManifest.xml File
It is XML configuration file of the application containing the following information:
41
Android Lab Manual for Novice
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.first_project.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>
42
Android Lab Manual for Novice
</application>
</manifest>
The executable for launching emulator is ‘emulator.exe’ which is located in the folder,
F:\eclipse\adt-bundle-windows-x86_64-20130917\sdk\tools
as shown below:
For launching AVD from command-line, start command-line and move to the folder
43
Android Lab Manual for Novice
F:\eclipse\adt-bundle-windows-x86_64-20130917\sdk\tools
44
Android Lab Manual for Novice
Accept the license agreement and click on button ‘Download Android Studio for Windows’
shown in the following figure:
45
Android Lab Manual for Novice
46
Android Lab Manual for Novice
Step 1: Right click on downloaded ‘.exe’ file and select the option ‘Run as Administrator’ from
the shortcut menu. The setup wizard launches as shown in the following figure:
47
Android Lab Manual for Novice
Step 2: Place a check mark next to ‘Android Virtual Device’ and click on ‘Next’ button
48
Android Lab Manual for Novice
Step 4: The next step prompts for specifying the start menu folder for the Android Studio
shortcut. Accept the default and click on ‘Install’ button.
49
Android Lab Manual for Novice
Step 6: After the installation is complete, place a check mark next to ‘Start Android Studio’
option and click on ‘Finish’ button.
On launching Android Studio, Android Studio Setup Wizard will start which displays a welcome
screen as shown in the following figure:
50
Android Lab Manual for Novice
Step 7: This step prompts for selection of installation type. Select ‘Standard’ and click on ‘Next’
button. The following dialog is displayed:
Step 8: The next screen prompts for the selection of UI theme which is by default IntelliJ.
Accept the default and click on ‘Next’ button to proceed.
51
Android Lab Manual for Novice
Step 9: In the next step review the settings, once verified, click on ‘Finish’ button to download
the selected components.
Step 10: The necessary components for launching Android Studio and setting up the
environment will be downloaded as shown in the following figure:
52
Android Lab Manual for Novice
After download is complete click on ‘Finish’ button. This completes the procedure for installing
and setting up Android Studio.
Android View
By default the project files are displayed in an Android view which is organized according to
different file types for ease of navigation.
Gradle
Gradle is the Android Studio build tool which takes different source files, compiles and packages
them into an ‘apk’ file which is the deployment unit of Android. It is used for automating the
process of program compilation.
All the three are java build automation tools. Ant is strictly a build tool with no dependency
management. The major benefit offered by Ant is its flexibility. Ant doesn’t impose any coding
conventions or project structures. But the downside is no dependency management.
On the other hand Maven is build automation tool with dependency management tool. Maven
relies on conventions and provides predefined commands.
Gradle is a dependency management and a build automation tool which was built upon the
concepts of Ant and Maven which combines best of both worlds – Ant’s flexibility and Maven’s
features. Unlike Ant and Maven, Gradle does not use XML files which led to the smaller
53
Android Lab Manual for Novice
54
Android Lab Manual for Novice
Alternatively, select File → New → New Project from the main menu as shown in the following
figure:
55
Android Lab Manual for Novice
56
Android Lab Manual for Novice
Enter the name of the project in the ‘Application name’ text box and click on ‘Next’ button.
In the next screen accept the default ‘Phone and Tablet’ for Android Target Devices and click
on ‘Next’ button.
57
Android Lab Manual for Novice
Accept the default activity name as ‘MainActivity’ and layout name as ‘activity_name’ and click
on ‘Finish’ button.
Android Studio will start creating the project as demonstrated in the following figure:
After the gradle build process is complete the following screen is displayed:
58
Android Lab Manual for Novice
59
Android Lab Manual for Novice
As seen from the above generated code, ‘MainActivity’ class is derived from
‘AppCompatActivity’ class.
As seen from the above figure, AppCompatActivity class is directly derived from
FragmentActvity class.
Activity is the fundamental block of creating Android Application. Activity is the base Class of
all other Activities as shown in the following figure:
60
Android Lab Manual for Novice
From the above figure it is clear that, AppCompatActivity inherits FragmentActivity and
FragmentActivity inherent Activity.
Hence,
If you want the backported Material Design look, use AppCompatActivity
If not, but you want nested fragments, use FragmentActivity
If not, use Activity
The ‘app’ folder is the root folder which consists of the following sub-folders:
src folder contains all the source code and resource files for the module in various sub-
folders shown below:
o java – This folder contains the packages containing java classes with source code
of the application classes.
Assets Folder
This folder contains files which are to be compiled into an ‘apk’ file as-is.
61
Android Lab Manual for Novice
The following figure shows the default layout of the application. The layout can be manipulated
from two different views:
Design View - XML view through coding
62
Android Lab Manual for Novice
Gradle Scripts
In the ‘Android’ view, the ‘Gradle Scripts’ section contains two important Gradle scripts:
build.gradle (module)
build.gradle (project)
The file build.gradle (module) defines module specific build configurations while build.gradle
(project) defines build configurations global to all the modules.
63
Android Lab Manual for Novice
64
Android Lab Manual for Novice
The following dialog is displayed which lists locations of SDK and JDK.
65
Android Lab Manual for Novice
The description of different sub-folders of Android SDK folder is given in the following table:
66
Android Lab Manual for Novice
67
Android Lab Manual for Novice
68
Android Lab Manual for Novice
This section describes the content of different folders constituting Android SDK.
add-ons Folder
This folder hosts additional libraries such as Google Maps as shown below:
69
Android Lab Manual for Novice
docs Folder
This folder contains Android SDK API reference documentation.
The important file in this folder is ‘index.html’ shown in the following figure:
70
Android Lab Manual for Novice
Platforms Folder
The heart of Android SDK folder is ‘platforms’ which contains SDK real file for
each platform which contains the following sub-folders:
o Skins folder contains the Android emulator skin,
o Templates folder is the default template project to create,
o Android.jar is the main framework file in this version
Platform Tools
Platform-tools folder holds some general tools, such as ADB, and AAPT, Aidl,
DX file,fastboot etc.
Tools Folder
7 important tools in the ‘tools’ sub-folder of ‘sdk’ folder are described below:
71
Android Lab Manual for Novice
ddms (Davlik Debug Monitor Server) tool is used to start the Android debugger,
Such as logcat, screenshots and file manager
draw9patch is the Android platform scalable PNG image tool
SQLite3 tool is used to operate SQLite database
monkeyrunner is a good application of pressure test,
mksdcard is a simulator tool for SD image creation
emulator is the main program of Android simulator,
traceview is an important Android platform debugging tool.
Android Platforms
The following figure depicts the android platforms installed on the current system:
72
Android Lab Manual for Novice
Build-Tools Folder
This folder contains the tools required for building Android apps. All the build tools are located
in the ‘build-tools’ sub-folder of ‘sdk’ folder. To point out important tools in this folder are:
dx.bat, aapt.exe, aidl.exe, dexdump.exe etc. It includes the complete set of development and
debugging tools for the Android SDK like emulator, sdcard, sqlite and apk builder etc.
Tools Folder
This folder includes the complete set of development and debugging tools for Android.
73
Android Lab Manual for Novice
Note: If you are deploying for a API 19 device, you should also have the Android SDK platform
19.
The quick glance at the few important SDK tools, build tools and platform tools is shown below:
SDK Tools:
Platform Tools:
1. adb
2. fastboot
3. dmtracedump
4. etc1tool
5. sqlite3
Build Tools:
1. adb
2. aidl, aapt, dexdump, and dx
3. bmgr
4. logcat
When the widget is selected in the layout the table listing the frequently used properties of a
widget is displayed as shown in the following figure:
74
Android Lab Manual for Novice
To view all the properties of a control, click on the link, ‘View all properties’. The following
table listing all the properties of a control is displayed:
75
Android Lab Manual for Novice
If you try to change the ID of a widget in design view, the following dialog box is displayed for
updating all references to the widget in R file and other source files referencing the widget.
76
Android Lab Manual for Novice
In the current system, all Android Studio projects are stored in the location
C:\Users\Lenovo1\AndroidStudioProjects
of hard drive as shown in the following figure:
77
Android Lab Manual for Novice
When Android SDK is installed a valid Android system image should already be installed in
Android SDK Manager. If due to some reason the system image is not installed, then it can be
installed manually by launching Android SDK Manager.
C:\Users\Lenovo1\AppData\Local\Android\sdk\tools
and locate the file ‘android.bat’ and double-click on it to launch Android SDK Manager.
Android SDK Manager is launched as shown in the following figure. As can be seen from the
following figure, for the android-25 platform, the SDK is installed but the system images are
missing.
78
Android Lab Manual for Novice
For installing system images for android-25 platform, select the required images by placing a
check mark next to the image as shown in the following figure (Atom_64 or ARM) abd scroll to
the bottom.
79
Android Lab Manual for Novice
Depending on the no. of packages selected the caption of the button will change. In the current
example 17 packages are selected. Hence the caption of the button will change to ‘Install 17
Packages’.
Click on ‘Install 17 Packages’
80
Android Lab Manual for Novice
The installation commences as shown in the above figure and the missing SDK and system
images are installed.
For creating a virtual device in Android Studio there are two options:
82
Android Lab Manual for Novice
1. Selecting the option Tools → Android → Virtual Device Manager from main menu.
OR
2. Clicking on ‘Create New Virtual Device’ button in ‘Select Deployment Target’ window
which appearing on execution of Android application as shown in the following figure:
In the above window, click on ‘Create New Virtual Device’ button. The following window
appears for selecting the hardware device, since Android application can be executed on variety
of hardware devices including tablet, TV, wearable device apart from phone. In the dialog that
appears select ‘Phone’.
83
Android Lab Manual for Novice
In the next screen that appears select the system image and click on ‘Next’ button.
84
Android Lab Manual for Novice
85
Android Lab Manual for Novice
Adopting any of these methods displays the following dialog for selecting the deployment target
which can be a real device or one of the virtual devices created earlier. The dialog lists all the
available virtual devices as shown in the following figure:
86
Android Lab Manual for Novice
From the list of virtual devices displayed above, select an AVD with the name ‘MCA’ created
earlier. The emulator starts up as shown in the following figure:
and the application gets deployed on the virtual device as shown in the following figure:
87
Android Lab Manual for Novice
As shown in the above figure, the shortcut key for achieving the same task is Shift + F12.
2. The recently created projects are displayed as shown in the following figure. If the
project is listed in the recent projects list, select it. Otherwise, select the option ‘Open an
existing Android Studio project’ shown in following figure:
88
Android Lab Manual for Novice
89
Android Lab Manual for Novice
Android Debug Bridge (adb) is a versatile command-line tool that lets you communicate with a
device (an emulator or a connected Android device). The adb command facilitates a variety of
device actions, such as
installing apps
debugging apps, and
it provides access to a Unix shell that you can use to run a variety of commands on a
device.
Working of ADB
90
Android Lab Manual for Novice
When the ADB client starts it first checks whether the server process is running. If not it
will start a new server process.
The server listens to all commands sent from ADB client across port 5037.
The emulators are searched by scanning odd numbered ports in the range 5555 to 5585
which consists of ports used by first 16 emulators.
Note: Each emulator uses two contiguous ports, even port for console connections and
odd port for ADB connections. For example, the following emulator uses the port 5554
for console connection and 5555 for ADB connection.
Once the server establishes a connection to the device ‘adb’ command can be used to
access the devices.
For listing all ADB command, start command prompt, change to the folder
F:\eclipse\adt-bundle-windows-x86_64-20130917\sdk\platform-tools
91
Android Lab Manual for Novice
adb
If the device is not up and running, has just started then the following output is generated:
92
Android Lab Manual for Novice
If the device is up and running then the output generated is shown in the following figure:
adb shell
93
Android Lab Manual for Novice
Without starting emulator if this command is issued then the error message ‘device not found’ is
generated as shown in the following figure:
adb kill-server
94
Android Lab Manual for Novice
As shown in the above figure, if the command ‘adb devices’ is issued when no daemon process
is running, the daemon process is started automatically on port 5037.
Alternatively, the daemon process can be started by issuing the following command:
adb start-server
and then any ADB command can be executed as shown in the following figure:
For sending command to a device with serial no, ‘emulator-5554’ use the following command:
95
Android Lab Manual for Novice
am command
You can also issue an activity manager command directly from adb without entering a remote
shell using the following syntax:
For instance, Android Studio uses the following command for executing the project using
Activity Manager as shown in the following figure:
96
Android Lab Manual for Novice
The syntax for changing the display size of a device is shown below:
This command is helpful for testing your app across different screen sizes by mimicking a small
screen resolution using a device with a large screen, and vice versa.
Example:
am display-size 1280x800
The syntax for changing the display density of a device is shown below:
display-density dpi
This command is helpful for testing your app across different screen densities on high-density
screen environment using a low density screen, and vice versa.
Example:
am display-density 480
97
Android Lab Manual for Novice
Within an adb shell, you can issue commands with the package manager (pm) tool to perform
actions and queries on application packages installed on the device. While in a shell, the syntax
is:
pm <command>
You can also issue a package manager command directly from adb without entering a remote
shell. For example:
98
Android Lab Manual for Novice
99
Android Lab Manual for Novice
100
Android Lab Manual for Novice
101
Android Lab Manual for Novice
The following command is used for creating a user with the name ‘pgn’.
adb shell pm create-user pgn
This command is used for creating a new ADB user. Create a new user with the given
user_name, printing the new user identifier of the user
102
Android Lab Manual for Novice
103
Android Lab Manual for Novice
The first column displays the string created by ADB to uniquely identify the device and
its port no. The string has the following format ‘emulator - <port_no>’ where port no is
the port used by the emulator for console connection.
The second column displays the state of the device which can be one of the following:
104
Android Lab Manual for Novice
105
Android Lab Manual for Novice
106
Android Lab Manual for Novice
Android APIs
After the Tools section you’ll see sections for each Android API. Typically when a new version
of the Android operating system is released, Google also updates the APIs which allow you to
develop with the latest features and fixes. You’ll see the Android version listed (i.e. 4.4.2) along
with the API level (API 19) as shown in the following figure:
107
Android Lab Manual for Novice
SDK Platform
The SDK Platform for a given API level allows you to compile against that version of Android.
Newer platforms require newer versions of the SDK Platform-tools and SDK Tools which is why
we need to keep those up to date.
These are Java samples included with each API level which can be installed on need basis.
System Images
These are system images that can be used with Android virtual devices. On later API levels, both
ARM and x86 images are included. The x86 images will run significantly faster and should be
preferred over the ARM equivalents. The images prefixed with ‘Google APIs’ include the
Google Play Services runtime and are useful for testing Google Play Services features such as
mapping. These versions are recommended over the ‘plain’ versions.
Note – the System Images take up a significant amount of disk space so you should only install
them if you’re using them.
Google APIs
Most API levels include a package called Google APIs. This includes additional documentation,
samples and libraries for the Google APIs for that version of Android for Java developers. These
libraries are only needed if you’re coding using the Google APIs.
108
Android Lab Manual for Novice
Extras
The final section is Extras. The packages in this section include extra functionality and tools you
can optionally use during development as shown in the following figure:
109
Android Lab Manual for Novice
Note – devices must have the Google Play Services Runtime installed to use these additional
APIs. Almost all new Android devices include the runtime - notable exclusions include the
Kindle Fire devices. Generally, Android emulators don’t include the Google Play Services
runtime by default but it can be installed separately.
Note - for some devices, you may need to install device specific drivers provided by the
manufacturer. USB debugging is somewhat inconsistent on Windows 8.x, it can be unreliable to
connect and some devices tend to work more reliably than others (ie Nexus). The driver isn’t
used on OSX.
D:\android\adt-bundle-windows-x86-20130522\adt-bundle-windows-x86-20130522\sdk\tools
110
Android Lab Manual for Novice
The SDK Manager can also be launched from eclipse menu. Launch eclipse and select Window
→ Android SDK Manager as shown in the following figure:
111
Android Lab Manual for Novice
112
Android Lab Manual for Novice
113
Android Lab Manual for Novice
am start –n com.example.hello/.MainActivity
114
Android Lab Manual for Novice
The prime steps involved in launching android applications from command-line are listed below:
The output generated after launching the ‘hello’ project from command-line is shown in the
following figure:
115
Android Lab Manual for Novice
Creating SD Card
The command for creating SD card is
116
Android Lab Manual for Novice
Working with external storage in the Android emulator could be a little tricky and the
documentation is not easy to find. I’ll try to give a brief walk through of the steps needed to
create a SD card image, mount the image in Linux, put content on it and use it in the emulator.
In both the 1.1 and 1.5 version of the SDK there is a tool called mksdcard located in the ‘<SDK
Install Dir>/tools’ folder. Simply run the following command:
117
Android Lab Manual for Novice
To be able to put content on to the card you can mount the card in Linux. It will then simply
appear as a folder in the file system.
Then mount the card as a loopback device using the following command:
With content we usually mean media content like images and videos. Images and videos are
located in a folder called ‘/dcim/Camera’. You could of course add any content to the card.
When you are done copying your files be sure to mount the card otherwise it will not be usable
from the emulator.
Google added something called Android Virtual Device (AVD) to the SDK 1.5. To create a new
AVD using our newly created SDcard image run the following:
Target 2 means that we want to use the 1.5 API features in the device. Now we simply fire up the
emulator and start using our content:
118
Android Lab Manual for Novice
119
Android Lab Manual for Novice
Enter the following command in ADB shell to list all connected devices:
adb devices
To connect to the emulator ‘emulator-5554’ enter the following command in ADB shell:
Open another command window and launch ADB shell. For connecting to the emulator
‘emulator-5556’ enter the following command in ADB shell:
120
Android Lab Manual for Novice
If the command is issued without specifying the target device ‘adb’ generates an error as shown
in the following figure:
To copy a file or directory and its sub-directories from the device, do the following:
121
Android Lab Manual for Novice
To copy a file or directory and its sub-directories to the device, do the following:
Replace local and remote with the paths to the target files/directory on your development
machine (local) and on the device (remote). For example:
122
Android Lab Manual for Novice
The Android SDK is made of mostly off-the-shelf components, plus some purpose-built
components. In many cases, configurations, plug-ins, and extensions adapt these components to
Android. The Android SDK is a study in the efficient development of a modern and complete
SDK. Google took this approach to bring Android to market quickly. You will see this for
yourself as you explore the components of the Android SDK. Eclipse, the Java language,
QEMU, and other preexisting platforms, tools, and technologies comprise some of the most
important parts of the Android SDK.
In creating the simple program that confirms that your SDK installation is correct, you have
already used many of the components of the SDK. Here we will identify and describe the
components of the SDK involved in creating your program, and other parts you have yet to use.
The Android Debug Bridge (adb) is a program that enables you to control both emulators and
devices, and to run a shell to execute commands in the environment of an emulator or device.
Adb is especially handy for installing and removing programs from an emulator or device.
The Dalvik Debug Monitor Server (DDMS) is a traffic director between the single port that
Eclipse (and other Java debuggers) looks for to connect to a Java Virtual Machine (JVM) and the
several ports that exist for each Android device or virtual device; DDMS is also a traffic
controller for each instance of the Dalvik virtual machine (VM) on each device. The DDMS also
provides a collection of functionality that is accessible through a standalone user interface or
through an interface embedded in Eclipse via the ADT plug-in.
When you invoke the DDMS from the command line, you will see something similar to the
window shown below. The following figure shows the Dalvik Debug Monitor running in
standalone mode.
123
Android Lab Manual for Novice
A list of devices and virtual devices, and the VMs running on those devices
In the upper-left pane of the DDMS window, you will see listed the Android devices you
have connected to your PC, plus any AVDs you have running. Listed under each device
or virtual device are the tasks running in Dalvik VMs.
VM information
Selecting one of the Dalvik VMs running on a device or virtual device causes information
about that VM to be displayed in the upper-right pane.
124
Android Lab Manual for Novice
Thread information
Information for threads within each process is accessed through the Threads tab in the
upper-right pane of the DDMS window.
Filesystem explorer
You can explore the filesystem on a device or virtual device using the DDMS filesystem
explorer, accessible through the “File explorer” menu item in the Devices menu. It
displays the file hierarchy in a window similar to the one shown above.
The Emulator Control tab in the upper-right pane of the DDMS window enables you to
‘fake’ a phone call or text message in an emulator.
Screen capture
The ‘Screen capture’ command in the Device menu fetches an image of the current
screen from the selected Android device or virtual device.
Logging
The bottom pane of the DDMS window displays log output from processes on the
selected device or virtual device. You can filter the log output by selecting a filter from
among the buttons on the toolbar above the logging pane.
A set of commands in the Device menu enables you to command the device or virtual
device to dump state for the whole device, an app, or the mobile radio.
125
Android Lab Manual for Novice
Eclipse enables you to create specific project types, including several kinds of Java projects. The
ADT plug-in adds the ability to make and use Android projects. When you make a new Android
project, the ADT plug-in creates the project file hierarchy and all the required files for the
minimal Android project to be correctly built. For Android projects, the ADT plug-in enables
Eclipse to apply components of the ADT plug-in to editing, building, running, and debugging
that project.
In some cases, components of the SDK can be used with Eclipse or in a standalone mode. But in
most of the Android application development cases covered in this book, the way these
components are used in or with Eclipse will be the most relevant.
The ADT plug-in has numerous separate components, and, despite the connotations of a “plug-
in” as a modest enhancement, it’s a substantial amount of software. Here we will describe each
126
Android Lab Manual for Novice
significant part of the ADT plug-in that you will encounter in using Eclipse for developing
Android software.
Layouts for user interfaces in Android applications can be specified in XML. The ADT plug-in
adds a visual editor that helps you to compose and preview Android layouts. When you open a
layout file, the ADT plug-in automatically starts this editor to view and edit the file. Tabs along
the bottom of the editing pane enable you to switch between the visual editor and an XML editor.
In earlier versions of the Android SDK, the Android Layout Editor was too limited to be of much
use. Now, though, you should consider using visual editing of Android layouts as a preferred
way of creating layouts. Automating the specification of layouts makes it more likely that your
layouts will work on the widest range of Android devices.
In Android projects, a manifest file is included with the project’s software and resources when
the project is built. This file tells the Android system how to install and use the software in the
archive that contains the built project. The manifest file is in XML, and the ADT plug-in
provides a specialized XML editor to edit the manifest.
Other components of the ADT Eclipse plug-in, such as the application builders, can also modify
the manifest.
Other Android XML files that hold information such as specifications for menus or resources
such as strings, or that organize graphical assets of an application, have specialized editors that
are opened when you open these files.
127
Android Lab Manual for Novice
Eclipse projects are usually built automatically. That means you will normally not encounter a
separate step for turning the source code and resources for a project into a deployable result.
Android requires Android-specific steps to build a file you can deploy to an Android emulator or
device, and the ADT plug-in provides the software that executes these steps. For Android
projects, the result of building the project is an .apk file. You can find this file for the test project
created earlier in this chapter in the bin subfolder of the project’s file hierarchy in your Eclipse
workspace.
The Android-specific builders provided in the ADT plug-in enable you to use Java as the
language for creating Android software, while running that software on a Dalvik VM that
processes its own bytecodes. That is, among other things these builders do, they turn the Java
bytecode output of the Java compiler into Dalvik bytecodes. They also create .apk files, which
have a different structure and content than .jar files.
When you run or debug an Android project from within Eclipse, the .apk file for that project is
deployed and started on an AVD or Android device, using the adb and DDMS to communicate
with the AVD or device and the Dalvik runtime environment that runs the project’s code. The
ADT plug-in adds the components that enable Eclipse to do this.
The DDMS
In The Dalvik Debug Monitor Server (DDMS) the Dalvik Debug Monitor was described and
how to invoke the DDMS user interface from the command line. The DDMS user interface is
also available from within Eclipse. You can access it by using the Window→Open
Perspective→DDMS command in the Eclipse menu. You can also access each view that makes
up the DDMS perspective separately by using the Window→Show View menu and selecting, for
example, the LogCat view.
128
Android Lab Manual for Novice
AVDs are made up of QEMU-based emulators that emulate the hardware of an Android device,
plus Android system images, which consist of Android software built to run on the emulated
hardware. AVDs are configured by the SDK and AVD Manager, which sets parameters such as
the size of emulated storage devices and screen dimensions, and which enables you to specify
which Android system image will be used with which emulated device.
AVDs enable you to test your software on a broader range of system characteristics than you are
likely to be able to acquire and test on physical devices. Because QEMU-based hardware
emulators, system images, and the parameters of AVDs are all interchangeable parts, you can
even test devices and system images before hardware is available to run them.
129
Android Lab Manual for Novice
QEMU
QEMU is the basis of AVDs. But QEMU is a very general tool that is used in a wide range of
emulation systems outside the Android SDK. While you will configure QEMU indirectly,
through the SDK and AVD Manager, you may someday need to tweak emulation in ways
unsupported by the SDK tools, or you may be curious about the capabilities and limitations of
QEMU.
QEMU is a general-purpose emulator system. The Android SDK provides controls over the
configuration of QEMU that make sense for creating emulators that run Android system images.
The SDK and AVD Manager provides a user interface for you to control QEMU-based AVDs.
In addition to the major tools you are likely to use in the normal course of most development
projects, there are several other tools in the SDK, and those that are used or invoked directly by
developers are described here.
Hierarchy Viewer
The Hierarchy Viewer displays and enables analysis of the view hierarchy of the current activity
of a selected Android device. This enables you to see and diagnose problems with your view
hierarchies as your application is running, or to examine the view hierarchies of other
applications to see how they are designed. It also lets you examine a magnified view of the
screen with alignment guides that help identify problems with layouts.
Layoutopt
Layoutopt is a static analyzer that operates on XML layout files and can diagnose some problems
with Android layouts.
130
Android Lab Manual for Novice
Monkey
Monkey is a test automation tool that runs in your emulator or device. You invoke this tool using
another tool in the SDK: adb. Adb enables you to start a shell on an emulator or device, and
Monkey is invoked from a shell, like this:
This invocation of Monkey sends 500 random events to the specified application (specified by
the package name) after waiting for a debugger to be attached.
sqlite3
Android uses SQLite as the database system for many system databases and provides APIs for
applications to make use of SQLite, which is convenient for data storage and presentation.
SQLite also has a command-line interface, and the sqlite3 command enables developers to dump
database schemas and perform other operations on Android databases.
These databases are, of course, in an Android device, or they are contained in an AVD, and
therefore the sqlite3 command is available in the adb shell.
keytool
keytool generates encryption keys, and is used by the ADT plug-in to create temporary debug
keys with which it signs code for the purpose of debugging. In most cases, you will use this tool
to create a signing certificate for releasing your applications.
Zipalign
Zipalign enables optimized access to data for production releases of Android applications. This
optimization must be performed after an application is signed for release, because the signature
affects byte alignment.
131
Android Lab Manual for Novice
Draw 9-patch
A 9-patch is a special kind of Android resource, composed of nine images, and useful when you
want, for example, buttons that can grow larger without changing the radius of their corners.
Draw 9-patch is a specialized drawing program for creating and previewing these types of
resources.
android
The command named android can be used to invoke the SDK and AVD Manager from the
command line, as we described in the SDK installation instructions in The Android SDK. It can
also be used to create an Android project from the command line. Used in this way, it causes all
the project folders, the manifest, the build properties, and the ant script for building the project to
be generated.
132
Android Lab Manual for Novice
CHAPTER 2
Getting Acquainted With Android Basics
Activity
An activity is a class that represents a single GUI screen and handles user interaction with the UI.
Launcher Activity
If the application consists of multiple activities, then one of them should be registered as an
activity that is displayed when the application is launched. Such an activity is referred to as
“Launcher Activity”. The user can then navigate from the launcher activity to other activities in
an application.
133
Android Lab Manual for Novice
Service
Service is a time consuming task which executes in a background without requiring user
interaction and does not have any GUI of its own. Service can continue to execute in the
background even if the application which has started it is destroyed. If the application starts a
service, it is the responsibility of the application to stop it before terminating.
Content Provider
Content Providers are used to share data between different Android applications.
AndroidManifest.xml
Manifest is an application configuration file indexing the basic building blocks of an application.
It is an XML configuration file with the name AndroidManifest.xml. It encapsulates the
following details:
Name of the launcher activity
Names of the basic building blocks such as activity, service, broadcast receiver and
content provider
Application permissions etc.
It contains information about the different components making up an android application and
records activities (launcher activity), services, broadcast receivers, content providers, different
permissions required for application etc. The AndroidManifest.xml file contains information of
your package, including components of the application such as activities, services, broadcast
receivers, content providers etc.
134
Android Lab Manual for Novice
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.first_project.MainActivity"
android:label="@string/app_name" >
135
Android Lab Manual for Novice
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<application>
application is the sub-element of the manifest. It includes the namespace declaration. This
element contains several sub-elements that declares the application component such as activity
etc.
The commonly used attributes are of this element are icon, label, theme etc.
android:icon represents the icon for all the android application components.
android:label works as the default label for all the application components.
android:theme represents a common theme for all the android activities.
<activity>
activity is the sub-element of application and represents an activity that must be defined in the
AndroidManifest.xml file. It has many attributes such as label, name, theme, launchMode etc.
android:label represents a label i.e. displayed on the screen.
android:name represents a name for the activity class. It is required attribute.
136
Android Lab Manual for Novice
<intent-filter>
intent-filter is the sub-element of activity that describes the type of intent to which activity,
service or broadcast receiver can respond to.
<action>
It adds an action for the intent-filter. The intent-filter must have at least one action element.
<category>
It adds a category name to an intent-filter.
Intents
Intents are the messages connecting together different components of Android application.
Intents are used for invoking services both system level services and user-defined services. Few
actions performed by intents are:
starting a new service
Launching an activity
Displaying a web page
Broadcasting a message
Dialing a phone call etc.
Resources
Resources are static data such as layouts, menus, bitmaps, layouts, colors, styles, strings, images
etc. which are organized in separate sub folders under /res sub folder of the android application
project folder as shown in the following figure .
137
Android Lab Manual for Novice
APK File
An apk file is created by the framework automatically. If you want to run the android application
on the mobile, transfer and install it. All the resources reside in different folders under ‘res’
folder of a project folder as depicted in the following figure:
1 anim/
XML files that define property animations. They are saved in res/anim/ folder
and accessed from the R.anim class.
2 color/
XML files that define a state list of colors. They are saved in res/color/ and
accessed from the R.color class.
138
Android Lab Manual for Novice
3 drawable/
Image files like .png, .jpg, .gif or XML files that are compiled into bitmaps, state
lists, shapes, animation drawable. They are saved in res/drawable/ and accessed
from the R.drawable class.
4 layout/
XML files that define a user interface layout. They are saved in res/layout/ and
accessed from the R.layout class.
5 menu/
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
the R.menu class.
6 raw/
Arbitrary files to save in their raw form. You need to
call Resources.openRawResource() with the resource ID, which
is R.raw.filename to open such raw files.
7 values/
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.integer class.
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.
139
Android Lab Manual for Novice
8 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.
Views
Views are the UI elements drawn on the container.
Widgets
Widgets are the controls placed on the home screen of an Android application.
Fragments
Fragments represent the portion of UI in an activity. A fragment is a kind of sub-activity. An
activity can be divided into different sub-activities where each sub-activity is represented by a
fragment. An activity can display one or more fragments on the screen at the same time.
Layouts
Layouts control the organization of widgets on the container.
R Class
When the Android application is compiled, R class gets automatically generated, which
contains resource IDs for all the resources available in res/ sub-folder of a project folder. R class
can be used to access the resource using sub-directory and resource name or directly resource
ID.
It is the auto-generated file that contains IDs for all the resources of res directory. It is generated
by aapt(Android Asset Packaging Tool). Whenever you create any component on activity_main,
a corresponding ID is created in the R.java file which can be used in the Java Source file later.
140
Android Lab Manual for Novice
If you create any component in the activity_main.xml file, id for the corresponding component is
automatically created in this file. This id can be used in the activity source file to perform any
action on the component.
R.java file includes a lot of static nested classes such as menu, id, layout, attr, drawable, string
etc.
package com.example.launcher;
*/
141
Android Lab Manual for Novice
142
Android Lab Manual for Novice
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
}
}
As evident from the structure of R class, there is a nested class corresponding to each subfolder
contained under /res sub-folder of the android project folder.
143
Android Lab Manual for Novice
The syntax employed for accessing different resources contained in /res folder in both java
program and XML file using the resource name is shown in the following table:
Package Description
android.app Provides access to the application model and is the cornerstone
of all Android applications
android.content Facilitates content access, and messaging between applications
and application components.
android.os Provides applications with access to standard operating system
services including messages, system services and inter-process
communication.
android.view The fundamental building blocks of application user
interfaces.
android.view.View Listener interfaces for event handling.
144
Android Lab Manual for Novice
package com.example.helloandroid;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
145
Android Lab Manual for Novice
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
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;
}
The onCreate() method of Activity class is called when Activity class is first created. onCreate()
method is the first method of the activity life cycle methods which has the following prototype:
The overridden onCreate() method of MainActivity class performs the following two tasks;
1. Invokes super class onCreate() method.
2. Invokes setContentView() method for laying controls on layout. The setContentview()
method inflates the XML layout file and instantiates the objects and renders the layout.
146
Android Lab Manual for Novice
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/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>
<activity android:name="com.example.helloandroid.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>
147
Android Lab Manual for Novice
Bundle in Android`
Bundle is a class used for sharing data between different android activities. Bundle is a custom
Android hash map. It is commonly employed to preserve the activity’s data when the activity
gets destroyed (such as when its orientation gets changed) using key/value pair and retrieve back
and display when the activity is created again. The key allows the data to be retrieved back from
the Bundle.
In order to refer to any resource in ‘strings.xml’ file employ the syntax given below:
@string/<name>
Where, <name> is the name of the string resource.
For example, to refer to string resource with the name app_name use the syntax,
@string/app_name.
But the message for this string is defined in the ‘strings.xml’ file. The
@string/hello_world provides information about the textview message. The value of the
attribute hello_world is defined in the ‘strings.xml’ file.
148
Android Lab Manual for Novice
Layout File
The ‘activity_main.xml’ is a layout file available in res/layout directory which is referenced by
your application during building its interface. This file is modified very frequently to change the
layout of the application. The content of the file corresponding to default layout is shown
below:
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity"/>
</RelativeLayout>
This is an example of simple RelativeLayout. The TextView is an Android control used to build
the GUI and it have various XML attributes
like android:layout_width, android:layout_height etc. which are being used to set its width and
height etc.. The @string refers to the strings.xml file located in the res/values folder. Hence,
@string/hello_world refers to the hello string defined in the ‘strings.xml’ file, which is "Hello
World!".
On double-clicking the layout file, activity_main.xml in package explorer, it is opened in the
default editor. The editor has two views:
1. Graphical View
2. Text View
149
Android Lab Manual for Novice
Graphical Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/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" >
150
Android Lab Manual for Novice
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
Example:
The code for creating a view by inflating the layout is shown below:
151
Android Lab Manual for Novice
packagecom.example.hello;
*/
public static final intactivity_horizontal_margin=0x7f040000;
public static final intactivity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final intic_launcher=0x7f020000;
}
public static final class id {
public static final intaction_settings=0x7f080000;
}
public static final class layout {
public static final intactivity_main=0x7f030000;
}
152
Android Lab Manual for Novice
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
153
Android Lab Manual for Novice
APK File
An apk file is created by the framework automatically. If you want to run the android application
on the mobile, transfer and install it.
Manifest file
It contains information about package including components such as activities, services, content
providers etc.
154
Android Lab Manual for Novice
appropriate control class before accessing the properties. When the control is added to the layout,
the corresponding entry is created in R.java class which maps a control to the unique numeric ID.
The ID generated in R class can be accessed using the following syntax:
R.id.<control_name>
The above ID should be passed to findViewById() for obtaining reference to the control.
Example 1:
Suppose a layout contains a text view control with the ID ‘textView1’. The reference to the text
view control can be obtained using the following code:
Example 2:
Suppose a layout contains two edit text controls with the IDs ‘editText1’ and ‘editText2’. The
reference to the edit text controls can be obtained in java code using the following code:
The same logic can be applied for obtaining reference to other controls present on the layout.
MainActivity.java
↓
package com.example.hello;
import android.os.Bundle;
155
Android Lab Manual for Novice
import android.app.Activity;
import android.view.Menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
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;
}
}
2. In the design view or text view change the ‘Text’ property of ‘textView1’ control to
‘Hello Android’.
156
Android Lab Manual for Novice
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_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="150dp"
android:text="Hello Android"
android:textColor="#0000ff"
android:textSize="25sp" />
</RelativeLayout>
157
Android Lab Manual for Novice
For changing the text size and color, click on ‘View all properties’ link at the bottom of
‘Properties’ window to display additional properties. The properties are organized in the
alphabetical order of their names. Scroll down to text properties and change the ‘textColor’
property to ‘#0000ff’ and ‘textSize’ property to ‘24sp’ as shown in the following figure:
158
Android Lab Manual for Novice
Execute the application by pressing the key combination, Shift + F10 or by clicking on a tool
representing green left pointing triangle.
Select the virtual device ‘siber’ as the deployment target as shown in the following figure:
159
Android Lab Manual for Novice
160
Android Lab Manual for Novice
Constant Description
public static final int LENGTH_LONG Displays message for a long duration
public static final int LENGTH_SHORT Displays message for a short duration
161
Android Lab Manual for Novice
Alternately, the two statements can be combined into a single statement as shown below:
Toast.makeText(MainActivity.this, “Hello Android”, Toast.LENGTH_LONG).show();
162
Android Lab Manual for Novice
MainActivity.java
↓
package com.example.toast_demo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Toast;
@Override
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;
}
4. Select the project in the package explorer and select Project → Build Project from the
main menu as shown in the following figure:
163
Android Lab Manual for Novice
6. Execute the application, by selecting the project in package explorer and selecting Run
As → Android Application from the shortcut menu as shown below:
164
Android Lab Manual for Novice
165
Android Lab Manual for Novice
166
Android Lab Manual for Novice
The following sections explore the three different methods of handling click event in Android.
MainActivity.java
↓
package com.example.hello1;
import android.os.Bundle;
import android.app.Activity;
167
Android Lab Manual for Novice
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
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;
}
168
Android Lab Manual for Novice
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="105dp"
android:layout_marginTop="173dp"
android:gravity="top"
android:onClick="sayHello"
android:text="Click Me" />
</RelativeLayout>
169
Android Lab Manual for Novice
170
Android Lab Manual for Novice
171
Android Lab Manual for Novice
172
Android Lab Manual for Novice
Click on ‘Click Me’ button. The message ‘Hello Android’ is displayed in a Toast as shown in
the following figure:
173
Android Lab Manual for Novice
174
Android Lab Manual for Novice
Program:
1. Create a new Android application project with the name ‘hello4’. The structure of
‘MainActivity’ class is shown below:
2. Add a method to MainActivity class with the name sayHello() as shown below:
175
Android Lab Manual for Novice
MainActivity.java
↓
package com.example.hello4;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
@Override
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;
}
public void display(View v)
{
t.setText("Hello Android!");
}
}
176
Android Lab Manual for Novice
177
Android Lab Manual for Novice
178
Android Lab Manual for Novice
Program:
1. Create a new Android application project with the name ‘hello2’.
2. Place a Button control on the layout as shown below and set its Text property to ‘Click
Me’.
3. Modify the MainActivity class as shown below:
MainActivity.java
↓
package com.example.hello2;
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;
179
Android Lab Manual for Novice
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(this);
}
@Override
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;
}
@Override
public void onClick(View arg0) {
Toast t=Toast.makeText(MainActivity.this, "Hello android!",
Toast.LENGTH_LONG);
t.show();
}
}
180
Android Lab Manual for Novice
As shown in the above figure, there are two declarations of ‘OnClickListener’ interface, one
declaration is present in ‘android.view.View’ package and another declaration is present in,
‘android.content.DialogInterface’. Select the first option from the list displayed.
Note: The shortcut key for displaying the hint is placing the mouse on the text containing the
error (displayed in red) and pressing the key combination, Alt+Enter.
181
Android Lab Manual for Novice
From the hint displayed, select the option ‘Implement methods’. The following dialog is
displayed. Select the method and click on ‘OK’ button.
182
Android Lab Manual for Novice
Program :
Handling Click Event of a Button Using Anonymous Inner Class
1. Create a new Android application project with the name ‘hello2’.
2. Place an edit text control and a button control on the layout
3. Change the ‘Text’ property of a button control to ‘Say Hello’
183
Android Lab Manual for Novice
184
Android Lab Manual for Novice
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" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="Say Hello" />
</RelativeLayout>
On deploying the project in the emulator and clicking on ‘Say Hello’ button, the following
output is generated:
185
Android Lab Manual for Novice
186
Android Lab Manual for Novice
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
@Override
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;
}
}
187
Android Lab Manual for Novice
android:onClick="displayMessage"
188
Android Lab Manual for Novice
189
Android Lab Manual for Novice
@Override
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;
}
190
Android Lab Manual for Novice
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="36dp"
android:layout_marginTop="57dp"
android:text="MCA"
android:onClick="displayMessage" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_marginLeft="34dp"
android:layout_toRightOf="@+id/button1"
android:text="MBA"
android:onClick="displayMessage" />
</RelativeLayout>
Deploy the application on the emulator. On clicking button with the text ‘MCA’, the following
output is generated.
191
Android Lab Manual for Novice
192
Android Lab Manual for Novice
Click on button with caption ‘MBA’. The message ‘Hello MBA!’ is displayed as shown in the
following figure:
Now, click on button with caption ‘MCA’. The message ‘Hello MCA!’ is displayed as shown in
the following figure:
193
Android Lab Manual for Novice
Debug messages are displayed in blue color. Informative messages are displayed in green color
and error messages are displayed in red color.
The following tabled depicts the different methods of Log class for displaying messages of
different severity.
Method Name Description
d Writing debug messages to application log.
i Writing informative messages to application log.
e Writing error messages to application log.
MainActivity.java
↓
package com.example.logfile;
194
Android Lab Manual for Novice
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
@Override
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;
}
}
Execute the application and click on the LogCat tab. Monitor the Tag corresponding to
‘MainActivity’ displaying the message.
195
Android Lab Manual for Novice
On deploying the application on target device, click on ‘Android monitor’ tab at the bottom and
click on ‘logcat’ tab.
MainActivity.java
↓
package com.example.log_messages;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
@Override
196
Android Lab Manual for Novice
@Override
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;
}
}
On deploying the application in the emulator, the following output is generated on selecting
‘error’ from drop-down list:
197
Android Lab Manual for Novice
On selecting ‘debug’ and ‘info’ from drop-down list the output generated is shown below:
198
Android Lab Manual for Novice
Click on ‘Display Saved Filters View’ button located at the right corner as shown in the above
figure. ‘Saved Filters’ view is displayed as shown in the figure.
Click on green ‘+’ button to create a new filter. You can create the log filter based on one of the
following criterion:
Log Tag
Log Message
PID
Application Name and
Log Event
as shown in the following figure:
Enter the Tag Name as ‘Group1’ to filter the messages belonging to ‘Group1’.
Similarly create ‘Group2’ filter containing the messages with the tag ‘Group2’.
199
Android Lab Manual for Novice
Enter ‘Group’ in the search field and select ‘Error’ from the drop-down list as shown in the
following figure. The following output is generated:
On selecting ‘info’ from the drop-down list, the following output is generated:
200
Android Lab Manual for Novice
On selecting ‘debug’ from the drop-down list, the following output is generated:
The TextView control provides several methods for changing the attributes of a text displayed by
it such as text color, text size, text alignment etc. as depicted in the following table:
201
Android Lab Manual for Novice
t1=(TextView)findViewById(R.id.textView1);
t1.setTextColor(Color.RED);
t1.setGravity(Gravity.CENTER);
t1.setTextSize(0, 24);
t1.setText("Center");
t2=(TextView)findViewById(R.id.textView2);
t2.setTextColor(Color.GREEN);
t2.setGravity(Gravity.LEFT);
t2.setTextSize(0, 36);
t2.setText("Left");
t3=(TextView)findViewById(R.id.textView3);
t3.setTextColor(Color.BLUE);
t3.setGravity(Gravity.RIGHT);
t3.setTextSize(0, 48);
t3.setText("Right");
MainActivity.java
↓
package com.example.color;
import android.os.Bundle;
import android.widget.*;
import android.graphics.*;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
202
Android Lab Manual for Novice
t2=(TextView)findViewById(R.id.textView2);
t2.setTextColor(Color.GREEN);
t2.setGravity(Gravity.LEFT);
t2.setTextSize(0, 36);
t2.setText("Left");
t3=(TextView)findViewById(R.id.textView3);
t3.setTextColor(Color.BLUE);
t3.setGravity(Gravity.RIGHT);
t3.setTextSize(0, 48);
t3.setText("Right");
}
@Override
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;
}
203
Android Lab Manual for Novice
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"
android:text="TextView" />
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="75dp"
android:text="TextView" />
204
Android Lab Manual for Novice
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="86dp"
android:text="TextView" />
</RelativeLayout>
205
Android Lab Manual for Novice
2. Place three plain text controls (located in TextFields tab) and a button control (located in
Form Widgets tab) on the layout.
EditText e1,e2,e3;
Button b;
206
Android Lab Manual for Novice
e1=(EditText)findViewById(R.id.editText1);
e2=(EditText)findViewById(R.id.editText2);
e3=(EditText)findViewById(R.id.editText3);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
int n1=Integer.parseInt(e1.getText().toString());
int n2=Integer.parseInt(e2.getText().toString());
int sum=n1+n2;
e3.setText(String.valueOf(sum));
}
catch(NumberFormatException e)
{
}
}
}
);
207
Android Lab Manual for Novice
MainActivity.java
↓
package com.example.add;
import android.os.Bundle;
import android.widget.*;
import android.app.Activity;
import android.view.Menu;
import android.view.View.*;
import android.view.*;
208
Android Lab Manual for Novice
e3.setText(String.valueOf(sum));
}
catch(NumberFormatException e)
{
}
}
}
);
}
@Override
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;
}
}
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
209
Android Lab Manual for Novice
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="87dp"
android:layout_marginTop="55dp"
android:orientation="vertical" >
</LinearLayout>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:ems="10"
android:gravity="center_vertical|center_horizontal" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
210
Android Lab Manual for Novice
android:layout_below="@+id/linearLayout1"
android:layout_marginTop="34dp"
android:ems="10"
android:gravity="center_vertical|center_horizontal" />
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2"
android:layout_marginTop="64dp"
android:ems="10"
android:gravity="center_vertical|center_horizontal" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText3"
android:layout_marginTop="54dp"
android:layout_toRightOf="@+id/linearLayout1"
android:text="Add" />
</RelativeLayout>
211
Android Lab Manual for Novice
212
Android Lab Manual for Novice
Enter the two numbers and click on ‘Add’ button. The following output is generated:
TextView t;
EditText e;
Button b;
ScrollView s;
String output;
213
Android Lab Manual for Novice
t=(TextView)findViewById(R.id.textView1);
e=(EditText)findViewById(R.id.editText1);
b=(Button)findViewById(R.id.button1);
s=(ScrollView)findViewById(R.id.scrollView1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
int n=Integer.parseInt(e.getText().toString());
for (int i=1;i<=n;i++)
{
if ((n % i)==0)
{
output=String.format("%d\n", i);
t.append(output);
}
}
}
catch(NumberFormatException e)
{
}
}
}
);
214
Android Lab Manual for Novice
MainActivity.java
↓
package com.example.factors;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.Menu;
import android.view.View;
import android.view.View.*;
import android.view.*;
import android.widget.Button;
import android.widget.*;
215
Android Lab Manual for Novice
{
try
{
int n=Integer.parseInt(e.getText().toString());
for (int i=1;i<=n;i++)
{
if ((n % i)==0)
{
output=String.format("%d\n", i);
t.append(output);
}
}
}
catch(NumberFormatException e)
{
}
}
}
);
}
@Override
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;
}
}
216
Android Lab Manual for Novice
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/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" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="52dp"
android:ems="10"
android:gravity="center_vertical|center_horizontal" />
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginTop="64dp"
android:layout_toLeftOf="@+id/button1" >
</ScrollView>
217
Android Lab Manual for Novice
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="34dp"
android:text="Find" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/scrollView1"
android:layout_marginTop="36dp"
android:text="Factors"
android:textSize="20sp" />
</RelativeLayout>
218
Android Lab Manual for Novice
219
Android Lab Manual for Novice
Calendar calendar;
int day,month,year;
TextView t;
t=(TextView)findViewById(R.id.textView1);
220
Android Lab Manual for Novice
MainActivity.java
↓
package com.example.datepicker;
import java.util.Calendar;
@Override
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;
}
221
Android Lab Manual for Novice
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/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_alignParentTop="true"
222
Android Lab Manual for Novice
android:layout_centerHorizontal="true"
android:layout_marginTop="53dp"
android:textSize="30sp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="Display Date"
android:onClick="display"
/>
</RelativeLayout>
223
Android Lab Manual for Novice
224
Android Lab Manual for Novice
linear_layout1.xml
↓
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff0000"
android:gravity="center_horizontal"
android:text="RED"
android:textSize="30sp"/>
225
Android Lab Manual for Novice
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00ff00"
android:gravity="center_horizontal"
android:text="GREEN"
android:textSize="30sp"/>
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#0000ff"
android:gravity="center_horizontal"
android:text="BLUE"
android:textSize="30sp"/>
</LinearLayout>
In the MainActivity class change the last statement of onCreate() method to the statement shown
below in bold and italic.
MainActivity.java
↓
package com.example.linearlayout;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
226
Android Lab Manual for Novice
@Override
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;
}
}
227
Android Lab Manual for Novice
Enter the name of the file as ‘linear_layout1’ as shown above and click on ‘OK’ button.
Enter the code shown above in ‘linear_layout1.xml’ file.
Modify MainActivity.java file to use the new layout.
228
Android Lab Manual for Novice
1. In the above application, right-click on the ‘layout’ folder under ‘res’ folder and create a
new layout with the root element <LinearLayout> with the name ‘linear_layout2’ as
shown below:
2. Add five text view controls to the layout with the ‘Text’ property set to ‘RED’,
‘GREEN’, ‘BLUE’, ‘YELLOW’ and ‘MAGENTA’, respectively and the background set
to ‘#ff0000’,’#00ff00’, ‘#0000ff’, ‘#ffff00’ and ‘#00ffff’, respectively.
229
Android Lab Manual for Novice
linear_layout2.xml
↓
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#ff0000"
android:gravity="center_vertical"
android:text="RED"
android:textSize="20sp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#00ff00"
android:gravity="center_vertical"
android:text="GREEN"
android:textSize="20sp" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#0000ff"
230
Android Lab Manual for Novice
android:gravity="center_vertical"
android:text="BLUE"
android:textSize="20sp" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#ffff00"
android:gravity="center_vertical"
android:text="YELLOW"
android:textSize="20sp" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#ff00ff"
android:gravity="center_vertical"
android:text="MAGENTA"
android:textSize="20sp" />
</LinearLayout>
In the MainActivity class change the statement shown in bold and italic to the one shown below:
setContentView(R.layout.linear_layout2);
231
Android Lab Manual for Novice
232
Android Lab Manual for Novice
1. In the above application, right-click on the ‘layout’ folder under ‘res’ folder and create a
new layout with the root element <TableLayout> with the name ‘table_layout’ as shown
below:
2. Add six text view controls to the layout with the ‘Text’ property set to ‘RED’, ‘GREEN’,
‘MAGENTA’, ‘BLUE’, ‘YELLOW’ and ‘CYAN’, respectively and the background set to
‘#ff0000’,’#00ff00’, ‘#ff00ff’, ‘#0000ff ‘, ‘#ffff00’ and ‘#00ffff’, respectively.
table_layout.xml
↓
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff0000"
android:text="RED"
233
Android Lab Manual for Novice
android:textSize="30sp" />
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00ff00"
android:text="GREEN"
android:textSize="30sp" />
<TextView
android:id="@+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff00ff"
android:text="Magenta"
android:textSize="30sp" />
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0000ff"
android:text="BLUE"
234
Android Lab Manual for Novice
android:textSize="30sp" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffff00"
android:text="YELLOW"
android:textSize="30sp" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00ffff"
android:text="Cyan"
android:textSize="30sp" />
</TableRow>
</TableLayout>
In the MainActivity class change the statement shown in bold and italic to the one shown below:
setContentView(R.layout.table_layout);
235
Android Lab Manual for Novice
236
Android Lab Manual for Novice
<TableRow
android:id="@+id/tableRow1"
android:layout_width="100px"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="One" />
<TextView
android:id="@+id/textView2"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="Two" />
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="100px"
android:layout_height="wrap_content" >
237
Android Lab Manual for Novice
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Four" />
</TableRow>
</TableLayout>
238
Android Lab Manual for Novice
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="52dp"
android:layout_y="106dp"
android:text="Password :" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
239
Android Lab Manual for Novice
android:layout_x="147dp"
android:layout_y="33dp"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="50dp"
android:layout_y="43dp"
android:text="User Name :" />
<EditText
android:id="@+id/editText2"
android:layout_width="155dp"
android:layout_height="wrap_content"
android:layout_x="146dp"
android:layout_y="97dp"
android:ems="10"
android:inputType="textPassword" />
</AbsoluteLayout>
In the MainActivity class change the statement shown in bold and italic to the one shown below:
setContentView(R.layout.absolute_layout);
240
Android Lab Manual for Novice
241
Android Lab Manual for Novice
Some important layout properties available to views in RelativeLayout are depicted in the
following table:
Layout Attribute Description
layout_above Places the view above the specified view id
layout_below Places the view below the specified view id
layout_toLeftOf Places the view left of the specified view id
layout_toRightOf Places the view right of the specified view id
layout_centerHorizontal If true, the view will be horizontally center
aligned within its parent.
layout_centerVertical If true, the view will be vertically center
aligned within its parent.
242
Android Lab Manual for Novice
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Button2" />
<Button
android:id="@+id/btn3"
243
Android Lab Manual for Novice
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button3" />
<Button
android:id="@+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Button4" />
<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button5" />
<Button
android:id="@+id/btn6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Button6" />
</RelativeLayout>
The layout generated from the above layout file is shown below:
244
Android Lab Manual for Novice
245
Android Lab Manual for Novice
android:layout_width="match_parent"
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button2" />
</RelativeLayout>
The layout generated from the above layout file is shown below:
246
Android Lab Manual for Novice
247
Android Lab Manual for Novice
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Button2" />
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button3" />
</RelativeLayout>
248
Android Lab Manual for Novice
The layout generated from the above layout file is shown below:
249
Android Lab Manual for Novice
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btn1"
android:layout_centerHorizontal="true"
android:text="Button2" />
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/btn2"
android:layout_alignBottom="@+id/btn2"
250
Android Lab Manual for Novice
android:text="Button3" />
<Button
android:id="@+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btn3"
android:text="Button4" />
<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@+id/btn1"
android:layout_toRightOf="@+id/btn1"
android:layout_alignParentRight="true"
android:text="Button5" />
</RelativeLayout>
The layout generated from the above layout file is shown below:
251
Android Lab Manual for Novice
android:layout_centerVertical
android:layout_centerHorizontal
android:layout_alignTop
android:layout_alignBottom
android:layout_alignLeft
android:layout_alignRight
252
Android Lab Manual for Novice
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/btn1"
android:text="Button2" />
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btn1"
android:text="Button3" />
<Button
253
Android Lab Manual for Novice
android:id="@+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/btn1"
android:text="Button4" />
<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/btn1"
android:text="Button5" />
</RelativeLayout>
The layout generated from the above layout file is shown below:
254
Android Lab Manual for Novice
The following layout organizes the nine buttons with ‘Text’ property set to 1..9 in a rectangular
grid of 3 rows and 3 columns.
255
Android Lab Manual for Novice
activity_main.xml
↓
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/GridLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnCount="3"
android:rowCount="3"
android:orientation="horizontal"
tools:context=".GridXMLActivity" >
<Button
android:id="@+id/button1"
android:layout_gravity="left|top"
android:text="1" />
<Button
android:id="@+id/button2"
android:layout_gravity="left|top"
android:text="2" />
<Button
android:id="@+id/button3"
android:layout_gravity="left|top"
android:text="3" />
<Button
android:id="@+id/button4"
android:layout_gravity="left|top"
android:text="4" />
256
Android Lab Manual for Novice
<Button
android:id="@+id/button5"
android:layout_gravity="left|top"
android:text="5" />
<Button
android:id="@+id/button6"
android:layout_gravity="left|top"
android:text="6" />
<Button
android:id="@+id/button7"
android:layout_gravity="left|top"
android:text="7" />
<Button
android:id="@+id/button8"
android:layout_gravity="left|top"
android:text="8" />
<Button
android:id="@+id/button9"
android:layout_gravity="left|top"
android:text="9" />
</GridLayout>
The layout generated from the above layout file is shown below:
257
Android Lab Manual for Novice
258
Android Lab Manual for Novice
The following layout creates a GridLayout of 5 rows and 5 columns and places three buttons
with the ‘Text’ property set to ‘Button1’, ‘Button2’ and ‘Button3’, respectively in the first
column of three rows
activity_main.xml
↓
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/GridLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnCount="5"
android:rowCount="5"
android:orientation="horizontal"
tools:context=".GridXMLActivity" >
<Button
android:id="@+id/btn1"
android:layout_column="1"
android:layout_row="1"
android:layout_gravity="left|top"
android:text="Button1" />
<Button
android:id="@+id/btn2"
259
Android Lab Manual for Novice
android:layout_column="1"
android:layout_row="2"
android:layout_gravity="left|top"
android:text="Button2" />
<Button
android:id="@+id/btn3"
android:layout_column="1"
android:layout_row="3"
android:layout_gravity="left|top"
android:text="Button3" />
</GridLayout>
The layout generated from the above layout file is shown below:
260
Android Lab Manual for Novice
activity_main.xml
↓
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/GridLayout1"
android:layout_width="wrap_content"
261
Android Lab Manual for Novice
android:layout_height="wrap_content"
android:columnCount="4"
android:orientation="horizontal"
android:rowCount="4"
tools:context=".GridXMLActivity" >
<TextView
android:id="@+id/textView1"
android:layout_column="1"
android:layout_gravity="left|top"
android:layout_row="1"
android:background="#ff0000"
android:text="Row 1 column 1" />
<TextView
android:id="@+id/textView2"
android:layout_column="2"
android:layout_gravity="left|top"
android:layout_row="1"
android:background="#00ff00"
android:text="Row 1 column 2" />
<TextView
android:id="@+id/textView3"
android:layout_column="3"
android:layout_gravity="left|top"
android:layout_row="1"
android:background="#0000ff"
android:text="Row 1 column 3" />
<TextView
262
Android Lab Manual for Novice
android:id="@+id/textView4"
android:layout_gravity="fill"
android:layout_columnSpan="4"
android:layout_rowSpan="2"
android:background="#00ffff"
android:text="Row 2,3 column 1,2,3" />
</GridLayout>
The layout generated from the above layout file is shown below:
263
Android Lab Manual for Novice
The following layout file employs FrameLayout for placing two overlapping child views, image
view and a text view.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/framelayout" >
<ImageView
android:id="@+id/frameImage"
264
Android Lab Manual for Novice
android:layout_width="200dp"
android:layout_height="300dp"
android:src="@drawable/ic_launcher"
android:layout_gravity="center"
android:clickable="true" />
<TextView
android:id="@+id/frameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Frame Layout"
android:textSize="15sp"
android:textStyle="bold"
android:visibility="visible"
android:layout_gravity="center" />
</FrameLayout>
265
Android Lab Manual for Novice
Change the statement shown in bold and italic with the following statement:
android:visibility="gone"
which hides the child view, TextView.
In the above example, the frame layout contains two overlapping views:
ImageView and
TextView
266
Android Lab Manual for Novice
Change the statement shown in bold and italic with the following statement:
android:visibility="gone"
which hides the child view, TextView.
On re-deploying the application on target device, the following output is generated:
267
Android Lab Manual for Novice
layout_gravity Attribute
It is the property of FrameLayout which enables controlling the position of child element.
MainActivity.java
↓
package com.example.framelayout;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
268
Android Lab Manual for Novice
@Override
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;
}
@Override
public void onClick(View arg0) {
if (t.getVisibility() == View.GONE)
t.setVisibility(View.VISIBLE);
else
t.setVisibility(View.GONE);
}
269
Android Lab Manual for Novice
270
Android Lab Manual for Novice
271
Android Lab Manual for Novice
MainActivity.java
↓
package com.example.framelayout;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
272
Android Lab Manual for Novice
t1.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL);
frame.addView(t1);
t2 = new TextView(this);
t2.setText("SIBER");
t2.setTextColor(Color.GREEN);
t2.setTextSize(30);
t2.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL);
frame.addView(t2);
t3 = new TextView(this);
t3.setText("SIBER");
t3.setTextColor(Color.BLUE);
t3.setTextSize(30);
t3.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL);
frame.addView(t3);
b.setOnClickListener(this);
}
@Override
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;
}
@Override
public void onClick(View arg0) {
switch(code)
{
273
Android Lab Manual for Novice
case 1:
t1.setVisibility(View.VISIBLE);
t2.setVisibility(View.GONE);
t3.setVisibility(View.GONE);
break;
case 2:
t2.setVisibility(View.VISIBLE);
t1.setVisibility(View.GONE);
t3.setVisibility(View.GONE);
break;
case 3:
t3.setVisibility(View.VISIBLE);
t1.setVisibility(View.GONE);
t2.setVisibility(View.GONE);
break;
}
code++;
if (code == 3)
code=1;
}
}
activity_main.xml
↓
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/framelayout" >
274
Android Lab Manual for Novice
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Next"
android:onClick=”next” />
</FrameLayout>
275
Android Lab Manual for Novice
276
Android Lab Manual for Novice
277
Android Lab Manual for Novice
278
Android Lab Manual for Novice
4. Click on the three ellipsis next to the property. The following dialog is displayed.
5. Expand ‘Drawable’ node and select the image ‘ic_launcher’. Click on ‘OK’ button.
6. Change the ‘Text’ property of the button control to ‘Android’.
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
279
Android Lab Manual for Novice
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" >
<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android"
android:drawableLeft="@drawable/ic_launcher"
android:drawablePadding="10dp"/>
</RelativeLayout>
280
Android Lab Manual for Novice
281
Android Lab Manual for Novice
String output;
TextView t=(TextView)findViewById(R.id.textView1);
for(int i=1;i<=50;i++)
282
Android Lab Manual for Novice
{
output=String.format("Line %d\n",i);
t.append(output);
}
MainActivity.java
↓
package com.example.lines;
import android.os.Bundle;
import android.widget.*;
import android.app.Activity;
import android.view.Menu;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
283
Android Lab Manual for Novice
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="76dp" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
284
Android Lab Manual for Novice
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/scrollView1"
android:layout_alignTop="@+id/scrollView1"
android:layout_marginLeft="36dp"
android:text="" />
</ScrollView>
</LinearLayout>
</RelativeLayout>
285
Android Lab Manual for Novice
To scroll through the data, click on the control and hold down left mouse button and drag the
mouse.
286
Android Lab Manual for Novice
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
287
Android Lab Manual for Novice
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
}
@Override
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;
}
}
288
Android Lab Manual for Novice
289
Android Lab Manual for Novice
MainActivity.java
↓
package com.example.launcher;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
@Override
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;
}
}
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
290
Android Lab Manual for Novice
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>
2. To create another activity, expand ‘src’ node in the package explorer, right-click on the
package ‘com.example.launcher’ and select New → Class from the shortcut menu as
shown in the following figure:
Enter the name of the class as ‘SecondActivity’ and click on ‘Finish’ button.
291
Android Lab Manual for Novice
The class with the name ‘SecondActivity’ is generated in the package com.example.launcher.
SecondActivity.java
↓
package com.example.launcher;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
292
Android Lab Manual for Novice
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
@Override
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;
}
}
To create a layout for the SecondActivity, right-click on ‘layout’ folder under ‘res’ folder and
select New → Android XML File from the shortcut menu as shown below:
293
Android Lab Manual for Novice
Enter the name of the file as ‘activity_second’ and click on ‘Finish’ button.
5. Place an ‘ImageView’ control and ‘TextView’ control with the text ‘Second Activity’ as
shown in the following figure:
294
Android Lab Manual for Novice
activity_second.xml
↓
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="125dp"
android:text="Second Activity"
android:textColor="#0000ff"
android:textSize="25sp" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="22dp"
android:layout_toLeftOf="@+id/textView1"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
295
Android Lab Manual for Novice
<activity
android:name="com.example.launcher.SecondActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="MainActivity"></activity>
296
Android Lab Manual for Novice
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_
LANDSCAPE);
MainActivity.java
↓
package com.example.screenorientation;
import android.os.Bundle;
import android.app.Activity;
297
Android Lab Manual for Novice
import android.content.pm.ActivityInfo;
import android.view.Menu;
@Override
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;
}
}
298
Android Lab Manual for Novice
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textSize="30sp" />
</RelativeLayout>
299
Android Lab Manual for Novice
300
Android Lab Manual for Novice
import android.graphics.Paint;
import android.view.View;
DemoView demoview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
demoview = new DemoView(this);
setContentView(demoview);
}
301
Android Lab Manual for Novice
paint.setAntiAlias(false);
paint.setColor(Color.BLUE);
canvas.drawCircle(20, 20, 15, paint);
paint.setStyle(Paint.Style.FILL);
canvas.drawText("Graphics Rotation", 40, 180, paint);
302
Android Lab Manual for Novice
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/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="32dp"
android:layout_marginTop="34dp"
android:text="Shake to change color" />
</RelativeLayout>
303
Android Lab Manual for Novice
304
Android Lab Manual for Novice
4. Enter the file name as ‘mylayout’ and accept other defaults. Click on ‘Finish’ button.
305
Android Lab Manual for Novice
mylayout.xml
↓
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
306
Android Lab Manual for Novice
android:layout_height="wrap_content"
android:text="Welcome To Android" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
</LinearLayout>
MainActivity.java
↓
package com.example.custom_toast;
import android.os.Bundle;
307
Android Lab Manual for Novice
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater li=getLayoutInflater();
View layout=li.inflate(R.layout.mylayout, (ViewGroup)findViewById(R.id.mylayout));
Toast t=new Toast(this);
t.setDuration(Toast.LENGTH_LONG);
t.setView(layout);
t.show();
}
@Override
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;
}
308
Android Lab Manual for Novice
309
Android Lab Manual for Novice
MainActivity.java
↓
package com.example.custom_toast;
import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
310
Android Lab Manual for Novice
t.setDuration(Toast.LENGTH_LONG);
t.setView(layout);
t.show();
}
@Override
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;
}
311
Android Lab Manual for Novice
312
Android Lab Manual for Novice
3. Place a button control, an edit control, and two text view controls on the layout.
4. Change the ‘Text’ property of button control to ‘Start’.
5. Declare the following variables in MainActivity class
313
Android Lab Manual for Novice
if (!e.getText().toString().equals(""))
startTime=Integer.parseInt(e.getText().toString())*1000;
text.setText(text.getText() + String.valueOf(startTime/1000));
timer = new MyTimer(startTime, interval);
if (!timer_flag) {
timer.start();
timer_flag = true;
start.setText("Start");
} else {
timer.cancel();
timer_flag = false;
start.setText("Reset");
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
text.setText("Time's up!");
time_eplapsed.setText("Time Elapsed: " + String.valueOf(startTime/1000));
}
@Override
314
Android Lab Manual for Novice
MainActivity.java
↓
package com.example.timer1;
import android.os.Bundle;
import android.os.CountDownTimer;
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.TextView;
315
Android Lab Manual for Novice
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.startbutton);
start.setOnClickListener(this);
text = (TextView) findViewById(R.id.timer);
e=(EditText) findViewById(R.id.editText1);
time_eplapsed = (TextView) findViewById(R.id.timeElapsed);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!e.getText().toString().equals(""))
startTime=Integer.parseInt(e.getText().toString())*1000;
text.setText(text.getText() + String.valueOf(startTime/1000));
timer = new MyTimer(startTime, interval);
if (!timer_flag) {
timer.start();
timer_flag = true;
start.setText("Start");
} else {
timer.cancel();
timer_flag = false;
316
Android Lab Manual for Novice
start.setText("Reset");
}
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
text.setText("Time's up!");
time_eplapsed.setText("Time Elapsed: " + String.valueOf(startTime/1000));
}
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
text.setText("Time remain:" + ((millisUntilFinished/1000)+1));
timeElapsed = (startTime - millisUntilFinished)/1000;
time_eplapsed.setText("Time Elapsed: "
+ String.valueOf(timeElapsed));
}
}
}
317
Android Lab Manual for Novice
activity_main.xml
↓
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/startbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start"
android:textAlignment="center">
</Button>
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp" >
<TableRow>
<TextView
android:id="@+id/timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="Time: "
android:textSize="20dp" />
</TableRow>
</TableLayout>
318
Android Lab Manual for Novice
<TextView
android:id="@+id/timeElapsed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Time elapsed: "
android:textSize="20dp" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter Time" >
<requestFocus />
</EditText>
</LinearLayout>
319
Android Lab Manual for Novice
Expand ‘General’ node and select the option ‘Existing Projects into Workspace’ as shown
below:
320
Android Lab Manual for Novice
321
Android Lab Manual for Novice
322
Android Lab Manual for Novice
This error can be handled by right-clicking on the project in package explorer and selecting
‘Properties’ from shortcut menu as shown in the following figure:
323
Android Lab Manual for Novice
Place a check mark in a specified Target Name and click on ‘OK’ button. The error disappears.
324
Android Lab Manual for Novice
CHAPTER 3
Exploring Resources in Android
All the resources of an application are stored in ‘res’ folder under project folder as shown in the
following figure:
The contents of ‘res’ folder are already discussed at depth in previous chapters.
When the Android project is created, by default the following resources are created:
activity_main.xml layout resource file for MainActivity and
main.xml menu resource file for main menu
The new resources can be created as required by right-clicking on the appropriate folder and
selecting New → Android XML file from the shortcut menu.
325
Android Lab Manual for Novice
‘Resources’ tab enables creating string resource visually in the editor. The auto-generated code
can be viewed in ‘strings.xml’ file. The list of already available string resources are displayed
under ‘Resource Elements’.
326
Android Lab Manual for Novice
Enter the name and value of a string resource and click on the resource under ‘Resource
Elements’ section as shown in the following figure.
The string resource with the name ‘course’ and value ‘MCA’ is created.
327
Android Lab Manual for Novice
The string resource with the name ‘message’ is added to ‘strings.xml’ file as shown below:
328
Android Lab Manual for Novice
strings.xml
↓
<?xmlversion="1.0"encoding="utf-8"?>
<resources>
<string name="app_name">message</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="message">Hello Android</string>
</resources>
In order to access the string in a Java code use the syntax given below:
R.string.message
3. Add a button control to the layout and change its ‘Text’ property to ‘Display Message’.
4. Add the following attribute to <button> element in activity_main.xml file.
android:onClick="displayMessage"
5. Declare the following control variable in MainActivity class.
TextView t;
t=(TextView)findViewById(R.id.textView1);
329
Android Lab Manual for Novice
@Override
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;
}
330
Android Lab Manual for Novice
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textSize="20sp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="102dp"
android:text="Display"
android:onClick="display"/>
</RelativeLayout>
331
Android Lab Manual for Novice
332
Android Lab Manual for Novice
Double-click on the file to open it in a text editor. The root node is ‘resources’ which contains
one or more ‘string’ child nodes with attribute name and value is its content as shown in the
following figure:
To create a new string resource, select ‘Open editor’ link that appears in the right corner of a
window and click on ‘+’ button to add new key. Specify the key and default value as shown in
the following figure and click on ‘OK’ button.
The string resource with the key ‘message’ is created as shown in the following figure:
333
Android Lab Manual for Novice
334
Android Lab Manual for Novice
<resources>
<!--
335
Android Lab Manual for Novice
<style name="CustomStyle">
<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">serif</item>
<item name="android:textSize">12pt</item>
<item name="android:textColor">#0000FF</item>
</style>
</resources>
336
Android Lab Manual for Novice
337
Android Lab Manual for Novice
338
Android Lab Manual for Novice
339
Android Lab Manual for Novice
340
Android Lab Manual for Novice
<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>
341
Android Lab Manual for Novice
<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>
Gradient.xml File
The structure of ‘gradient.xml’ layout file is shown below:
342
Android Lab Manual for Novice
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/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"
style="@style/CustomFontStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="85dp"
android:background="@drawable/gradient"
android:text="Button" />
</RelativeLayout>
343
Android Lab Manual for Novice
344
Android Lab Manual for Novice
345
Android Lab Manual for Novice
</shape></item>
</selector>
4. Create the file with the name ‘red.xml’ in ‘res/drawable-hdpi’ folder and enter the
following code:
346
Android Lab Manual for Novice
android:width="1dp"
android:color="#992f2f" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
</selector>
5. Create the file with the name ‘rounded.xml’ in ‘res/drawable-hdpi’ folder and enter the
following code:
347
Android Lab Manual for Novice
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="@drawable/red"
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" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
348
Android Lab Manual for Novice
android:layout_alignParentTop="true"
android:layout_marginTop="124dp"
android:ems="10"
android:background="@drawable/mystyle"
android:text="Define a Style and Apply to a View">
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:background="@drawable/red"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginLeft="90dp"
android:layout_marginTop="74dp"
android:text="Button" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="54dp"
android:background="@drawable/rounded"
android:text="Rounded Corners Gradient Button" />
</RelativeLayout>
349
Android Lab Manual for Novice
350
Android Lab Manual for Novice
351
Android Lab Manual for Novice
352
Android Lab Manual for Novice
353
Android Lab Manual for Novice
Select ‘String Array’ from the list of elements displayed and click on ‘OK’ button.
354
Android Lab Manual for Novice
Similarly add three more items with the string values, ‘MBA’, ‘MSW’, ‘M.Phil’.
After this the edit looks like this:
355
Android Lab Manual for Novice
Drag and drop ‘ListView’ control from the ‘Composite’ tab on the layout as shown in the
following figure:
The ListView control has the property called ‘Entries’ as shown in the following figure. This
property can be initialized with string array resource.
356
Android Lab Manual for Novice
For setting ‘Entries’ property click on three ellipsis next to the property. The following dialog is
displayed. Expand ‘Array’ element and select ‘courses’ from the list displayed. Click on ‘OK’
button.
The ‘Entries’ property of ListView control is set as shown in the following figure:
357
Android Lab Manual for Novice
To test, deploy the application on the emulator. The following output is generated:
OR enter the value ‘@array/courses’ for ‘entries’ property manually as shown in the
above figure.
Deploy the application on target device.
359
Android Lab Manual for Novice
Other menu resources can be created and stored in this folder. When the new project is created in
Android by default a main menu is created. The menu resource file with the name ‘main.xml’ is
created and stored in a folder ‘res/menu’ under project folder as shown in the following figure:
360
Android Lab Manual for Novice
361
Android Lab Manual for Novice
362
Android Lab Manual for Novice
363
Android Lab Manual for Novice
364
Android Lab Manual for Novice
Select the first option ‘Create a new element at the top level, in Menu’ as shown in the above
figure, select ‘Item’ option and click on ‘OK’ button. The new menu item is added to the menu
as shown in the following figure:
365
Android Lab Manual for Novice
The default Id of the new menu item is ‘@+id/item1’. To change it to the required Id, click on
the ‘Browse..’ button next to it.
You can directly enter ID of your choice in Id text field. ‘+’ sign indicates that if the ID is not
present then it will be created.
Create the following menu items:
Menu Item ID String Resource Name String Resource Value
‘@+id/open file_open Open
‘@+id/save file_save Save
366
Android Lab Manual for Novice
367
Android Lab Manual for Novice
Select ‘Item’ and click on ‘OK’ button. Enter the title of submenu as ‘File’.
368
Android Lab Manual for Novice
Select the second option ‘Create a new element in the selected element’ and click on ‘OK’
button.
369
Android Lab Manual for Novice
Select ‘Item’ and click on ‘OK’ button. Enter the title of the menu item as ‘Open’.
370
Android Lab Manual for Novice
Note: In the case of any errors, clean and build the project.
371
Android Lab Manual for Novice
</menu>
372
Android Lab Manual for Novice
373
Android Lab Manual for Novice
374
Android Lab Manual for Novice
375
Android Lab Manual for Novice
With the ‘Sub-Menu’ selected click on ‘Add’ button. The following dialog is displayed.
376
Android Lab Manual for Novice
With the ‘group1’ item selected, choose ‘single’ option from ‘Checkable behavior’ drop-down
list.
With the ‘group1’ selected, click on ‘Add’ button and add an item with title ‘Line’ as shown
below:
377
Android Lab Manual for Novice
378
Android Lab Manual for Novice
379
Android Lab Manual for Novice
380
Android Lab Manual for Novice
2. Enter the name of the menu as ‘shape_menu’ and click on ‘Finish’ button.
381
Android Lab Manual for Novice
382
Android Lab Manual for Novice
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
383
Android Lab Manual for Novice
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.shape_menu, menu);
return true;
}
384
Android Lab Manual for Novice
Right-click on ‘menu’ node and select New → Menu resource file from shortcut menu.
385
Android Lab Manual for Novice
Enter the name of the resource file as ‘main_menu’ and click on ‘OK’ button.
The palette contains the following items for creating the menu,
386
Android Lab Manual for Novice
Menu Item
Menu
Group
The component tree contains main menu as shown in the following figure:
For adding menu items to the main menu, drag the menu item from the palette and drop it onto
the menu inside component tree. The GUI is updated accordingly as shown in the following
figure:
387
Android Lab Manual for Novice
Select the menu item in the layout and in the properties table enter the ‘id’ and ‘title’ for the
menu as shown in the following figure:
The two required properties of menu item are ‘id’ and ‘title’.
388
Android Lab Manual for Novice
Similarly create other menu items using the ‘id’ and ‘title’ shown in the following table:
The code generated and stored in ‘main_menu.xml’ file is shown in the following figure:
389
Android Lab Manual for Novice
<item android:title="Save"
android:id="@+id/item3" />
<item android:title="Exit" />
</menu>
@Override
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, menu);
return true;
}
390
Android Lab Manual for Novice
Note: The order of menu items can be changed by dragging and dropping the menu item to the
required location in component tree.
o Create a menu item with id ‘item2’ and title ‘Checked’ and set the properties as
shown below:
391
Android Lab Manual for Novice
o Create a menu item with id ‘item3’ and title ‘disabled’ and set the properties as
shown below:
Note: ‘-‘ in the property indicates that the property is not set.
Add onCreateOptionsMenu() method to MainActivity class.
On deploying the application on target device, the following output is generated:
392
Android Lab Manual for Novice
393
Android Lab Manual for Novice
394
Android Lab Manual for Novice
Drag and drop a menu item on ‘menu’ in component tree. Change it’s ‘Text’ property to
‘Edit’.
Drag and drop a menu on ‘Edit’ menu.
Drag and drop three menu items on ‘Edit’ menu and set their ids and titles as shown in
the following table:
After this, the component tree looks like the one shown in the following figure:
395
Android Lab Manual for Novice
main_menu.xml
<item android:title="File"
android:id="@+id/item1" >
<menu >
<item android:title="New"
android:id="@+id/item1"
android:visible="true"
android:showAsAction="always" />
<item android:title="Open"
android:id="@+id/item2"
android:visible="true"
android:showAsAction="always" />
<item android:title="Save"
android:id="@+id/item3"
android:visible="true"
android:showAsAction="always" />
<item android:title="Exit"
android:id="@+id/item4"
android:visible="true"
android:showAsAction="always" />
</menu>
</item>
<item android:title="Edit" >
<menu >
<item android:title="Cut"
396
Android Lab Manual for Novice
android:id="@+id/item5" />
<item android:title="Copy"
android:id="@+id/item6" />
<item android:title="Paste"
android:id="@+id/item7" />
</menu>
</item>
</menu>
397
Android Lab Manual for Novice
398
Android Lab Manual for Novice
showAsAction – always
icon - @drawable/exit
Click on the ellipsis next to icon text field and select the image from the ‘drawable’ folder as
shown in the following figure:
399
Android Lab Manual for Novice
The following code is generated for adding an icon to the menu item:
400
Android Lab Manual for Novice
In the current example, we will create a group of mutually exclusive shape menu items.
Create a new project in Android Studio with the name ‘MenuGroup’.
Create a ‘menu’ folder under ‘res’ folder and create a new menu resource file with the
name ‘main_menu.xml’.
Drag and drop ‘group’ item from the palette on the menu.
Drag and drop three menu items on ‘group’ item of component tree and set their ids and
titles as shown in the following table:
401
Android Lab Manual for Novice
main_menu.xml
↓
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single" >
<item android:title="Line"
android:id="@+id/item1"
android:checked="true"
/>
<item android:title="Circle"
android:id="@+id/item2"/>
<item android:title="Rectangle"
android:id="@+id/item3"/>
</group>
</menu>
402
Android Lab Manual for Novice
403
Android Lab Manual for Novice
6. Drag and drop three items on the group as depicted in the following table:
Menu ID Menu Title
Item1 Line
Item2 Circle
Item3 Rectangle
The property settings for the three menu items are shown in the following figures:
404
Android Lab Manual for Novice
405
Android Lab Manual for Novice
406
Android Lab Manual for Novice
407
Android Lab Manual for Novice
Drag and drop a ‘Menu Item’ from palette on ‘menu’ in component tree and set its
‘Text’ property to ‘Color’.
Drag and drop a ‘Menu’ from palette on ‘Color’ in component tree.
Drag and drop a ‘Group’ from palette on ‘menu’ item below ‘Color’ in component tree.
Drag and drop three menu items on ‘group’ item item below ‘Color’ item in component
tree and set their ids and titles as shown in the following table:
408
Android Lab Manual for Novice
↓
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Shape" >
<menu >
<group android:checkableBehavior="single" >
<item android:title="Line"
android:id="@+id/item1"
android:checked="true" />
<item android:title="Circle"
android:id="@+id/item2" />
<item android:title="Rectangle"
android:id="@+id/item3" />
</group>
409
Android Lab Manual for Novice
</menu>
</item>
<item android:title="Color" >
<menu >
<group android:checkableBehavior="single">
<item android:title="Red"
android:id="@+id/item4"
android:checked="true" />
<item android:title="Green"
android:id="@+id/item5" />
<item android:title="Blue"
android:id="@+id/item6" />
</group>
</menu>
</item>
</menu>
410
Android Lab Manual for Novice
411
Android Lab Manual for Novice
412
Android Lab Manual for Novice
Example:
Creating Course and Language Menus
The component trees of ‘course_menu’ and ‘language_menu’ are shown in the following
figures:
MainActivity.java
↓
package com.example.lenovo1.custommenu;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
413
Android Lab Manual for Novice
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.course_menu, menu);
getMenuInflater().inflate(R.menu.language_menu, menu);
return true;
}
}
On deploying the project on the target device the following output is generated:
getMenuInflater().inflate(R.menu.course_menu, menu);
414
Android Lab Manual for Novice
in ‘MainActivity.xml’ file.
415
Android Lab Manual for Novice
CHAPTER 4
Working with Dialogs in Android
‘android.widget’ package supports the following dialog classes for improving the user
experience of an end user:
AlertDialog
DatePickerDialog
TimePickerDialog
ProgressDialog
CharacterPickerDialog
• Android AlertDialog class can be used to display the dialog message with ‘OK’ and
‘Cancel’ buttons. It can be used to interrupt and ask the user about his/her choice to
continue or discontinue.
• Android AlertDialog is composed of three regions: title, content area and action buttons.
Android ‘AlertDialog’ class is the subclass of ‘Dialog’ class. The following figure depicts
the hierarchy of AlertDialog class.
416
Android Lab Manual for Novice
Method Description
setTitle(CharSequence) This method is used to set the title of
AlertDialog.
setMessage(CharSequence) This method is used to set the message of
AlertDialog.
setIcon(int) This method is used to set the icon of
AlertDialog with the specified icon ID as
parameter.
417
Android Lab Manual for Novice
AlertDialog.Builder alertdialog;
418
Android Lab Manual for Novice
MainActivity.java
↓
package com.example.alertdialog;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
419
Android Lab Manual for Novice
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
420
Android Lab Manual for Novice
android:layout_height="wrap_content"
android:text="Alert Dialog Demo"
android:textSize="25sp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginRight="60dp"
android:layout_marginTop="58dp"
android:text="Exit"
android:onClick="display"/>
</RelativeLayout>
422
Android Lab Manual for Novice
423
Android Lab Manual for Novice
private TextView t;
private Button b;
private int year, month, day;
t=(TextView) findViewById(R.id.textView1);
b=(Button) findViewById(R.id.button1);
final Calendar c= Calendar.getInstance();
424
Android Lab Manual for Novice
year=c.get(Calendar.YEAR);
month=c.get(Calendar.MONTH);
day=c.get(Calendar.DAY_OF_WEEK);
t.setText("Current Date is : "+(month+1)+"-"+day+"-"+year);
b.setOnClickListener(this);
425
Android Lab Manual for Novice
MainActivity.java
↓
package com.example.datepicker1;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
426
Android Lab Manual for Novice
@Override
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;
}
@Override
public void onClick(View arg0) {
new DatePickerDialog(MainActivity.this,dateListener,year,month,day).show();
Method 2:
The complete source code of MainActivity class is given below:
MainActivity.java
↓
package com.example.datepicker2;
import java.util.Calendar;
import android.os.Bundle;
427
Android Lab Manual for Novice
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
428
Android Lab Manual for Novice
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View arg0) {
new DatePickerDialog(MainActivity.this,this,year,month,day).show();
@Override
public void onDateSet(DatePicker arg0, int tyear, int tmonth, int tday) {
year=tyear;
month=tmonth;
day=tday;
t.setText("Current Date is : "+(month+1)+"-"+day+"-"+year);
}
}
429
Android Lab Manual for Novice
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp"
android:textSize="20sp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:text="Set Date" />
</RelativeLayout>
430
Android Lab Manual for Novice
431
Android Lab Manual for Novice
Click on ‘Display Date’ button. The ‘Date Picker’ dialog with the current date selected, is
displayed as shown in the following figure.
Select the required date and click on ‘OK’ button. The selected date is displayed in a text view
control as shown in the following figure:
432
Android Lab Manual for Novice
private TextView t;
private Button b;
private int hr, min;
t=(TextView) findViewById(R.id.textView1);
433
Android Lab Manual for Novice
b=(Button) findViewById(R.id.button1);
final Calendar c= Calendar.getInstance();
hr=c.get(Calendar.HOUR_OF_DAY);
min=c.get(Calendar.MINUTE);
t.setText("Current Time is : "+hr+":"+min);
b.setOnClickListener(this);
434
Android Lab Manual for Novice
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
435
Android Lab Manual for Novice
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View arg0) {
new TimePickerDialog(MainActivity.this,timeListener,hr,min,true).show();
}
Method 2:
The complete source code of ‘MainActivity’ class is given below:
MainActivity.java
↓
package com.example.timepicker;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
436
Android Lab Manual for Novice
import android.app.TimePickerDialog.OnTimeSetListener;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
@Override
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;
437
Android Lab Manual for Novice
@Override
public void onClick(View arg0) {
new TimePickerDialog(MainActivity.this,this,hr,min,true).show();
}
@Override
public void onTimeSet(TimePicker arg0, int hour, int minute) {
hr=hour;
min=minute;
t.setText("Current Time is : "+hr+":"+min);
}
}
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/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"
438
Android Lab Manual for Novice
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="56dp"
android:textSize="20sp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:text="Set Time" />
</RelativeLayout>
439
Android Lab Manual for Novice
Select the time and click on ‘Done’ button. The following output is generated:
440
Android Lab Manual for Novice
441
Android Lab Manual for Novice
442
Android Lab Manual for Novice
Button b1;
private ProgressDialog progress;
443
Android Lab Manual for Novice
//progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.setProgress(0);
progress.show();
MainActivity.java
↓
package com.example.progressbar;
444
Android Lab Manual for Novice
import android.os.Bundle;
public class MainActivity extends Activity {
Button b1;
private ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
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;
}
445
Android Lab Manual for Novice
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/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" >
446
Android Lab Manual for Novice
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="106dp"
android:text="Download"
android:onClick="download" />
</RelativeLayout>
447
Android Lab Manual for Novice
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
448
Android Lab Manual for Novice
Click on ‘DOWNLOAD’ button to display progress bar as shown in the following figure:
449
Android Lab Manual for Novice
Redeploy the application on the target device. Now, the following output is generated:
450
Android Lab Manual for Novice
Button button;
ProgressDialog progressDialog;
451
Android Lab Manual for Novice
@Override
public void onClick(View v) {
progressDoalog = new ProgressDialog(MainActivity.this);
progressDoalog.setMax(100);
progressDoalog.setMessage("Its loading....");
progressDoalog.setTitle("ProgressDialog bar example");
progressDoalog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDoalog.show();
new Thread(new Runnable() {
@Override
public void run() {
try {
while (progressDoalog.getProgress() <= progressDoalog
.getMax()) {
Thread.sleep(200);
handle.sendMessage(handle.obtainMessage());
if (progressDoalog.getProgress() == progressDoalog
.getMax()) {
progressDoalog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
452
Android Lab Manual for Novice
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
progressDoalog.incrementProgressBy(1);
}
};
});
MainActivity.java
↓
package com.example.progressdialog;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
Button button;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
453
Android Lab Manual for Novice
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMax(100);
progressDialog.setMessage("Its loading....");
progressDialog.setTitle("ProgressDialog bar example");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
new Thread(new Runnable() {
@Override
public void run() {
try {
while (progressDialog.getProgress() <= progressDialog
.getMax()) {
Thread.sleep(200);
handle.sendMessage(handle.obtainMessage());
if (progressDialog.getProgress() == progressDialog
.getMax()) {
progressDialog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
454
Android Lab Manual for Novice
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/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"
455
Android Lab Manual for Novice
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="34dp"
android:layout_toRightOf="@+id/textView1"
android:text="Start" />
</RelativeLayout>
456
Android Lab Manual for Novice
457
Android Lab Manual for Novice
458
Android Lab Manual for Novice
The parameter to onClick() method is View class object reference initialized with the button of
CharacterPickerDialog clicked by the user. To obtain the title of the button clicked by the user,
the View object must first be cast to a Button class and invoke getText() method as shown in the
following code snippet:
Button b=(Button)v;
String title=b.getText().toString();
459
Android Lab Manual for Novice
MainActivity.java
↓
package com.example.characterpickerdialog;
import android.app.Activity;
import android.os.Bundle;
import android.text.method.CharacterPickerDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Toast;
460
Android Lab Manual for Novice
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
461
Android Lab Manual for Novice
}
}
activity_main.xml
↓
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="103dp"
android:text="Select Character" />
</RelativeLayout>
462
Android Lab Manual for Novice
On clicking ‘Select Character’ button, the Character Picker dialog is displayed as shown below:
463
Android Lab Manual for Novice
464
Android Lab Manual for Novice
465
Android Lab Manual for Novice
Click on any character, the selected character is displayed in a Toast as shown below:
466
Android Lab Manual for Novice
References:
Learning Resources:.
1. http://developer.android.com/guide/developing/tools/avd.html
2. http://developer.android.com/guide/developing/tools/emulator.html
3. http://developer.android.com/tools/sdk/tools-notes.html
4. http://www.qemu.org
5. https://developer.android.com/tools/revisions/build-tools.html
6. http://developer.android.com/guide/developing/tools/index.html
7. http://developer.android.com/guide/developing/tools/layoutopt.html.
8. https://developer.android.com/google/play-services/index.html
9. https://developer.android.com/tools/support-library/index.html
10. http://developer.android.com/guide/developing/tools/monkey.html.
11. https://www.tutorialspoint.com/android/index.htm
12. https://developer.android.com/guide
13. https://www.javatpoint.com/android-tutorial
14. https://www.studytonight.com/android
15. https://www.tutlane.com/tutorial/android
16. https://www.vogella.com/tutorials/android.html
17. https://www.w3school.in/android-studio/
18. https://examples.javacodegeeks.com/android/android-tutorial-beginners-with-examples/
19. https://abhiandroid.com/programming/
20. https://developer.android.com/reference/android/view/WindowManager.LayoutParams
21. http://developer.android.com/guide/developing/tools/adb.html#shellcommands.
22. http://developer.android.com/guide/developing/tools/zipalign.html.
23. http://developer.android.com/guide/developing/tools/draw9patch.html.
24. http://developer.android.com/guide/developing/other-ide.html#CreatingAProject.
467
This book is intended for a novice who is keen in getting first-hand information
about Android. The book is thought provoking which motivates the reader to
think out of the box and explore new features available in the application
framework.
The book is written in-line with the industry requirements and consists of 4
chapters from chapter 1 through 4.
Chapter 1 focuses on basic features and architecture of Android and provides
insight into execution of Android application. The main feature of the chapter
is setting up development environment which focuses on setting up ADT
bundled eclipse and Android Studio. Android application folder structure is
explored at depth. Downloading Android platforms and creating AVD for
testing Android applications are also discussed. Chapter concludes with
discussion of command-line tools, Android Debug Bridge (ADB), Activity
Manager and Package Manager.
Chapter 2 is devoted for basic building blocks of Android, core Android libraries
and different types of layouts understanding of which is crucial for developing
working application in Android. Anatomy of Android application is presented.
The structure of R class and basic elements of AndroidManifest.xml file where
the prime system configuration information resides are also discussed. The
main highlight of the chapter is more than one ways of handling events in
Android with are discussed along with suitable examples in each case.
Chapter 3 explores different types of resources available in Android. Basic
steps involved in creating and using string resource, string array resource, style
resource and menu resource both in eclipse and Android Studio are discussed.
Finally
Chapter 4 provides an overview of various pre-defined dialogs available in
Android such as Alert Dialog, Date Picker Dialog,
Time Picker Dialog, Progress Dialog and Characer Picker Dialog which aid in
rapid application development and help in
rendering the application user friendly.
Academic
Evincepub
E Publishing