III.
BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
UNIT - I
INTRODUCTION TO ANDROID
Android:
Android is Google’s open source and free java based platform for mobile development.
It enables developer to build real world mobile application using Android software development
kit (SDK).
Android can run on Android phone/tablet/devices of different screen sizes and resolutions.
Android was initially developed by Android, Inc., a small Palo Alto, California company in
October 2003.
Google bought this company in July 2005 and released Android SDK in November 2007.
Android Versions:
Versions 1.0 and 1.1 were not released under specific code names.
Android code names are confectionery (sweets and chocolates collectively) themed and have been
in alphabetical order since 2009’s Android 1.5 cupcake, with most recent version.
Android versions should be listed below with version number, name, release date and API level.
Code Name Version Number Release Date API Level
Cup cake 1.5 April 27, 2009 3
Donut 1.6 Sept 15, 2009 4
Éclair 2.0 - 2.1 Oct 26, 2009 5-7
Froyo 2.2 - 2.2.3 May 20, 2010 8
Ginger bread 2.3 - 2.3.7 Dec 6, 2010 9 - 10
Honey comb 3.0 - 3.2.6 Feb 22, 2011 11 - 13
Ice cream Sandwich 4.0 - 4.0.4 Oct 18, 2011 14 - 15
Jelly bean 4.1 - 4.3.1 July 9, 2012 16 - 18
Kitkat 4.4 - 4.4.4 Oct 31, 2013 19 - 20
Lollipop 5.0 - 5.1.1 Nov 12, 2014 21 - 22
Marsh mallow 6.0 - 6.0.1 Oct 5, 2015 23
Nougat 7.0 - 7.1.2 Aug 22, 2016 24 - 25
Oreo 8.0 - 8.1 Aug 21, 2017 26 - 27
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 1
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Android 4.1 Jelly Bean:
Android 4.1 jelly bean SDK was released with new features for developers in July 2012.
Few of big features of this release include the following:
Project Butter:
It makes jelly bean UI faster and more responsive
It increases CPU performance whenever screen is touched.
Faster speech recognition:
Speech recognition is now faster and doesn’t require any network to convert voice into text.
User can dictate to device without internet connection.
Improved notification system:
Notification can be expanded or collapsed through variety of gestures and user can block
notifications is desired.
Notification includes action buttons that enable to call directly from notification menu
rather replying to email.
Supports new languages:
It includes support for several languages including Arabic, Hebrew, Hindi and Thai.
It supports bidirectional text.
Predictive keyboard:
On basis of current context, next word of message is automatically predicted.
Auto arranging home screen:
Icons and widgets automatically resize and realign as per existing space.
Helpful for visually impaired users:
Gesture mode combined with voice helps visually impaired users to easily navigate user
interface.
Improved camera app:
It includes new review mode of captured photos.
User can swipe in from right of screen to quickly view captured photos.
Better communication:
Two devices can communicate with near field communication (NFC) that is devices can
tap to share data.
Android devices can pair to Bluetooth devices that support by just tapping them together.
Improved Google Voice search:
It equipped with question and answer search method that helps in solving users queries.
Face lock:
Unlocks device when user looks at it. It prevents screen from blacking out.
Blink can used to conform that live person is unlocking device instead of photo.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 2
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Google now:
Provide users “just right information at just right time”.
It displays cards to show desired information automatically.
Examples: places card displays nearby restaurants and shops while moving.
Google play widgets:
Provides quick and easy access to movies, games, magazines and other media on device. It
supports new purchases on Google play.
Faster Google search:
Google search can be opened quickly from lock screen and from system bar by swiping up
and also tapping hardware search key if it is available on device.
Supports antipiracy:
This future supports developer in sense that applications are encrypted with device specific
key making it difficult to copy and upload them to internet.
Understanding Android Software Stack:
Android Operating System (software stack) is divided into five sections in four layers:
1. Linux kernel:
This is kernel on which Android is based.
This layer contains all low level device drivers for various hardware components of android
device.
2. Libraries:
These contain all code that provides main features of android OS.
SQlite libraries provide database support.
Web kit libraries provide functionalities for web browsing.
Surface manager library provides 2D and 3D graphics.
Free type library provides font support.
Media framework provides recording and playback of audio and video formats.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 3
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
3. Android runtime:
At same layer as libraries, android runtime provides set of core libraries that enable
developer to write android apps using java.
Android runtime also includes Dalvik virtual machine, which enables every android
application to run in it’s our process, with its own instance of Dalvik virtual machine.
Dalvik is specialized virtual machine designed for Android and optimized for battery
powered mobile devices with limited memory and CPU.
4. Application framework:
It exposes various capabilities of android OS to application developers. So that they can
make use of them in their applications.
It manages user interface and application resources.
5. Applications:
At this top layer, you will find applications that ship with device (such as phone, contents,
browser .....etc).
You will find applications that you download and install from Android Market.
Installing Android SDK:
For developing native android application you need to install the following four applications:
1. Java Development Kit (JDK)
It can download from http://oracle.com/technetwork/java/javasc/downloads/index.html.
2. Eclipse IDE
It can download from http://eclipse.org/dowmloads/.
3. Android platform SDK starter package
It can be downloading from http://developer.android.com/sdk/index.html.
4. Android Development Tools (ADT) plug in
It can download from http://developer.android.com/sdk/eclipse-adt.html. The plug-in
contains project templates and eclipse tools.
Android SDK is not full development environment and includes only core SDK tools, you need to
install platform tools and other components required for developing Android applications.
Go to http://developer.comsdk/index.html and download package installer_r18_windows.exe.
After downloading file, double click it. Android SDK manager window opens then select next
button to move next screen. It checks presence of JDK on computer.
If JDK is not found, download and Install JDK from http://www.oracle.com/technetwork/
java/javasc/downloads/index.html.
Select JDK link that suits your platform and double click then you see setup wizard screen. Select
next to see custom setup dialog box JDK installation.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 4
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Three categories of features (Development tools, source code an public JRE) are displayed and you
select from dropdown list to choose features you want to install.
Default location displayed is c:\program files\java\jdk1.8.0\,but you can use change button to
select another location.
Keep default settings and click next features are installed followed by dialog box with default
folder to install JRE (Java Runtime Environment).
Use change button to continue program in other location Select next button to continue. After java
installation Android SDK tools setup wizard automatically resumes.
If java is already installed before beginning with Android SDK installation, wizard deletes its
presence and displays version number of JDK on your machine.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 5
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Select next button, you get dialog box asking you to choose users, for which Android SDK is being
installed.
1. Install for anyone using this computer.
2. Install just for me.
Select install for anyone using this computer option and click next. Next dialog prompts you for
location to install Android SDK Tools.
Dialog box also displays default directory location for installing Android SDK tools as c:\Program
Files\Android\android-sdk which can change by selecting Browse button. Select next button to
continue.
Next dialog box asks you to specify start menu folder where you want the program’s short cuts to
appear as bellow.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 6
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Default folder name appears called Android SDK Tool. If you don’t want to make start menu
folder, select do not create short cuts check box. Select install button to begin installation of
Android SDK tools.
After installation, select net button, next dialog box tells you android SDK tools setup wizard
completed. Select finish to exit wizard.
Note that check box start SDK manager (to download system images) is checked by default it
means after finish clicked, Android SDK manager was launched.
Adding Platforms and Other Components:
In this step you see how to use Android SDK manager to download and Install important SDK
packages required for development environment.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 7
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Android SDK manager shows list of packages and their installation status. Dialog box shows
Android SDK tools package is already installed on machine.
Android SDK manager recommends platform by checking Android 4.1(API 16) and Google USB
driver package by default.
You can check more packages and uncheck existing packages to determine which API you want to
install. Select all packages listed under Extras and click install button to initiate installation.
Next dialog box shows list of packages that you have selected to install. You need to select accept
option followed by install button to begin installation
Android SDK manger log window appears showing downloading and installation progress. It also
shows list of Packages that have been loaded.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 8
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
After select close button, next dialog box is android SDK manger Shown below.
Dialog box conform that android SDK platform tools, android4.1 (API16) and its components have
been successfully installed. You do not need android SDK manager now, so you close it.
Android application is combination of several small components include java files, XML resource
and layout files, Manifest files and much more.
It is very time consuming to create all components manually. so, you can use following
applications to help you:
1. Eclipse IDE:
An IDE that makes task of creating java applications easy.
It provides complete platform for developing java applications with compiling, debugging
and testing support.
2. Android development tools (ADT) plug in:
Plug in that added to eclipse IDE and automatically creates necessary android files so you
can concentrate on process of application development.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 9
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
NOTE: Before you begin the installation of eclipse IDE, first set path of JDK (My Computer →
Properties→ Advanced tab →Environment variables→ System variables→ path (add path of JDK)
Installing Eclipse:
Eclipse IDE is Multilanguage software developing platform used for developing java applications.
Eclipse can be downloaded from following URL:http://www.eclipse.org/downloads/. Eclipse
classic and eclipse IDE for developers are recommended. Both JDK and eclipse must be same
version either 32 bit or 64 bit.
Eclipse is self contained executable files (to install it, eclipse is unzip to any desired folder).
To launch eclipse, run eclipse.exe file. Eclipse IDE starts by displaying logo followed by
workspace launcher dialog box.
Workspace launcher dialog prompts for location of workspace folder where eclipse project files
will store and it can be change by browse button.
Select Ok button to continue when eclipse finishes loading an eclipse welcome screen is displayed.
Select the curved-arrow icon at the top right of screen to go to workbench. You can see that all
windows in workbench (Package Explorer, Edit Window, Debug Window and Task List) are blank
at moment.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 10
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
These windows update their content as you develop android applications. Next step is installing
android development tools (ADT) plug-in.
Installing Android Development Tools (ADT) Plug-In:
Android development tools (ADT) is plug in for eclipse IDE that provides powerful integrated
environment to build android applications.
It integrates with eclipse to add functionality for creating, testing, debugging and deploying
android applications.
To install ADT plug in select help, install new software option from eclipse IDE. You see dialog
box asking for location of website from which you want to install new software.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 11
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Select add button to add website or repository location. An add repository dialog box appears as
shown below.
Enter name of repository in name textbox and in location box specify location of repository as
https://dl.ssl.google.com/android/eclipse/ and Click ok.
Eclipse accesses List of developers tools available at specified site and display it as shown below.
You can see developer Tools with four child node: Android DDMS, Android Development Tools,
Android Hierarchy Viewer and Android Traceview.
To install all above tools Select Parent node developer Tools and Select Next Button.
You see dialog box to Review Licences for ADT. Read license agreement. Select I accept terms as
agreement Radio Button if you agree with terms and conditions and select finish Button.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 12
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
ADT plug in is then downloaded and installed in eclipse after that you get software updates dialog
box asking to restart Eclipse.
Select Restart now Button from Software updates dialog box to make installation changes can take
effect.
Making ADT Plug in Functional:
To make ADT plug in functional inside eclipse, plug in needs to point to the Android SDK.
Launch IDE and select window preferences option.
In preferences dialog box select Android and set SDK location field to specify path where SDK is
installed on your disk.
On specifying path, list of SDK targets is displayed .You can now develop and test Android
application against any of displayed targets.
You need to select apply and click OK to reload SDK targets and close preference window. Now
eclipse has ADT plug in attached.
Creating Android Virtual Devices:
Android Virtual Device (AVD) represents device configuration. There are many Android Devices,
each with different configuration.
You can create AVD that represent their configuration after creating AVDs. You point to emulator
to each one when developing and testing application. AVDs are easiest way to test application with
various configurations
To create AVDs in eclipse, select window, AVD Manager Option. Android virtual device manager
dialog box opens, as shown.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 13
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Dialog box displays list of existing AVDs else you create new AVDs and manage existing AVDs
Select Create button to define new AVD dialog box. The fields are as follows:
1. Name - used to specify name of AVD.
2. Target - used to specify target API level. Application will be tested against specified
API level.
3. CPU/ABI - determines processor that we want to emulate on our device.
4. SD card - used for extending the storage capacity of devices. large files such as Audio
and video stored in SD card.
5. Snapshot - enable this option to avoid booting of emulator and starting it from last saved
snapshot. It is used to start emulator quickly.
6. Skin - used for setting screen size. You can try multiple skins to see if your
application works across different devices.
7. Hardware - used to set properties representing various optional hardware that present in
target device.
In AVD set name of AVD to demoAVD, choose Android 4.1 API level16 for target, set SD card to
64mb and leave default (WVGA800) for Skin.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 14
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
In hardware section three properties are already set for developing on selected target
Abstracted LCD density is set to 240
Max VM application heap size is set to 48
Device RAM size is set to 512
Finally, select the Create AVD button to see how to create the virtual device called demo AVD.
new AVD, demoAVD is created and displayed in list of existing AVDs, as shown
Creating the First Android Project:
To create an application, open Eclipse and choose File, New, Android application project or Click
the Android Project Creator icon on the eclipse toolbar, or select the File, New, other option.
A dialog box appears asking you to select the wizard you want to use for new application. Select
Android application project and click next. You see a dialog box asking for information about the
Android application, as shown below
In the Application Name box, enter the name of the application (HelloWorldApp). The project
Name box shows the name of the project automatically by default as application name box.
The Package name box shows the default package name, com.example.helloworldapp. it is unique
identifier, package name may contain uppercase or lowercase letters, numbers, underscores and
package begin with letters.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 15
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
From the Build SDK drop-down, select the version of Android most commonly used by your
target audience. Select the Android 4.1 (API 16) as the target platform.
From the Minimum Required SDK select the minimum version of the Android platform that is
required to run application.
Select the Create Project in Workspace check box. By default, the location is set to the workspace
specified when opening Eclipse for the first time.
After Clicking next, configure Launcher Icon is used for configuring the icon for the application.
The dialog shows three options — Image, Clipart and Text — to define icon for our application.
Clipart - It is selected by default showing one of the built-in clipart. Select the Choose
button to open the list of available cliparts.
Image - It is used to specify custom image as our application’s icon.
Text - It displays a text box where we can enter to represent our application. Select the
font button to change the font size and style.
Select Trim Surrounding Blank Space check box to remove the extra blank space around the
chosen image, clipart, or the text. A scroll-bar is also provided to specify padding around the icon.
The icon can be set to appear at the center of assigned space or can be cropped to accommodate the
assigned space. It also has buttons to make the icon appear as square or circle shape.
Other two buttons, Background Colour and Foreground Colour, are provided different colours of
the icon. After defining the icon, click next.
The next dialog prompts us to select whether we want to create an activity. To create activity,
dialog box asks whether we want to create a Blank Activity or Master Detail Flow activity.
The Blank Activity option creates a new blank activity, whereas the Master Detail Flow option
creates two master and detail fragments and two activities.
Select the Create Activity check box and the Blank activity option from the list and then click next.
Next dialog confirms the creation of the activity. The Android SDK assigns the default name
Main Activity to the newly created activity.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 16
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Layout file is assigned to the default name as activity_main. Title assigned to the activity by
default is Main activity. If you want to change name remove default name and enter new name.
Finally create the application by clicking Finish. After
application creation Package Explorer shows the files
automatically created by the ADT plug-in, as shown.
Now, we concentrate on the two files that play important
roles in all android applications:
1. The XML file, found in the res/layout folder – It
defines the user interface of the application. It contains
controls such as text view, Button and Checkbox that are
arranged on the display.
2. The java file, found in the src folder – It contains
action code of the controls defined in xml file. Data
entered by the user is fetched and processed with this
java file.
Idea for separating the user interface from the action
code is to isolate the presentation layer from the
business logic,it allows developers to change the user
interface without rewriting the code itself.
I frequently use several terms in xml and java files described in Table shown below
Term Description
Views are user interface (UI) controls that collectively make up the Screen of
View application. TextView, Buttons and edit text controls are all individually known as
views. Views are placed in containers known as layouts.
ViewGroups are extensions of the view class that can contain multiple Child views.
ViewGroup Examples of ViewGroup include LinearLayout, AbsoluteLayout, TableLayout,
RelativeLayout, FrameLayout and ScrollView.
Android applications must have at least one activity. Activity represents single
screen in an application and consists of one or more views. If more than one
Activity
activity in the application, they work independently. Activities in android are
usually started with an intent.
Intent is a message-passing mechanism telling the android application when user is
Intent asking it to do. It represents the action to execute in response to the event, along
with the data on which to perform the action.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 17
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Laying out the Application:
Screen of the application is defined by an XML file. The controls through which the desired
information is displayed to the user and through which the user interacts with the application are
defined in XML code.
To define a screen of an application, you open the activity_hello_world_app.xml file, which is
automatically created by the ADT plug-in in the res/layout folder.
When u double-click on the activity_hello_world_app.xml file, you see the graphical layout of the
application center window, as shown below.
There are two tabs at the bottom of the panel: Graphical Layout and activity_hello_world
_app.xml. The Graphical Layout tab shows the layout in the Eclipse’s visual Designer and the
activity_hello_world_app.xml tab shows the xml code of the layout file.
Using the Visual Designer:
Visual designer provided by eclipse displays the layout file graphically. On the left side of the
display, the designer shows a list of controls categorized in different categories.
you need to do is drag the desired control from the left side and drop it on the layout file. You can
also configure the controls by settings their properties.
The properties panel is hidden by default. To make it visible after you select Window, Show View,
Other, General, Properties option then all its properties is displayed in the properties panel.
Understanding the XML version of the Layout File:
The XML code of the layout file can be seen by selecting the activity_hello_world_app.xml tab at
the bottom of the panel. The default code is shown below.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 18
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@srting/hello"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
tools:context=".HelloWorldAppActivity"/>
</RelativeLayout>
RelativeLayout is the default layout and arranges the controls in relation to the existing controls.
xmlns:android defines Android namespace. It always set to http://schemas.android.com/apk/res/
android. Namespaces are for assigning unique identifications to application elements to avoiding
any collisions between element names.
Most basic UI control, TextView, which is commonly used for displaying information. In android,
the control that shows upon screen and is used for displaying information and handling events is
known as a Views. All Views are placed inside container.
The most common attributes required for laying out a screen view are Layout_width and
Layout_height. These attributes are also known as LayoutParams in the Android SDK. These
indicate height and width of view.
The two most common values for layout_width and layout_height are match_parent and
wrap_content constants.
match_parent - It fill as much space as possible on the screen based on the available space of
parent layout .
wrap_content - It take as much space as needed to show the View.
If you don’t provide values for these attributes, the Android applications will crash when rendering
the view.
Value of the attributes android:layout_centerHorizantal and android: layout_centerVertical are set
to “true” to make the TextView controls text appear at the horizontal and vertical center of view .
TextView control must be fetched from the strings resource files, strings.xml, defines in res/values
folder. The text hello in the strings.xml file is assigned to the TextView for display.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 19
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Defining Action Code through Java:
An Activity represents a Screen of the application and enables user interaction. While creating the
Application ,You defined the Activity name as HelloWorldAppActivity; hence the java file is
named HelloWorldAppActivity.java
Default Code in the Java Activity File HelloWorldAppActivity.Java as shown below
Package com.androidunleashed.helloworldapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class HelloWorldAppActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_world_app);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_hello_world_app, menu);
return true;
}
}
The Java file is created and maintained in the package com.androidunleashed.helloworldapp that
defined at the time of creation of application.
The file imports the desired class files and also inherits the Activity class. The onCreate() method
is invoked when the Activity is started.
Parameter Bundle saved Instance State refers to a bundle used to pass information between
different activities. If you don’t write super.onCreate() statement into the java file, you get a
runtime exception. It is needed for activity initialization.
User interface defined in the layout file activity_ hello_ world_app.xml is set as the content of an
activity file. The parameter R. layout. activity_ hello_ world_ app in the setContent() method
refers to the activity_hello_world_app.xml file of the project’s res/layout folder.
The character R in the parameter refers to the auto-generated R.java class file.
onCreateOptionsMenu () method dealing with menus.
Let’s keep the existing default code of activity_hello_world_app.xml and HelloWorldApp-
Activity.Java and run the application to see the output.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 20
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
To run the application, you need to create an Eclipse launch configuration and choose a virtual
device on which to run the application.
The Android ADT provides two options for creating launch configurations:
1. Run configuration- Used to run an application on a given device.
2. Debug configuration- Used to debug an application while it’s running on a given device.
To create an Eclipse launch configuration, select the Run, Debug configurations option. A Debug
configurations dialog box opens. Double-click the Android Application.
Wizard inserts new configuration named New_configuration shown below let’s rename the
configuration to HelloWorldApp_configuration. You need to specify the Android project name in
the project box.
From the Launch drop-down list in the Launch Action Section, Select the activity file
com.Androidunleashed.helloworldapp. HelloWorldAppActivity option, followed by the Apply
button.
Next, you need to define a device on which to run the application. Select the Target tab in the same
dialog box. You get the below Screen.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 21
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
The Deployment Target Selection Mode displays the following three options:
1. Always prompt to pick device – Allows you to choose the device or AVD to connect to when
using this launch configuration.
2. Launch on all compatible devices/AVDs – Deploys the application automatically on all the
compatible AVDs or devices available.
3. Automatically pick compatible device – Deploys the application on the AVDs that are
selected. If none of the AVDs are selected, the application is launched on the compatible
AVDs or devices available.
Select the third option, followed by selecting the demoAVD check box to test the application
against the Android 4.1 target.
After Selecting the AVD, Select the Apply button, followed by close button to save the launch
configuration file.
Running the Application:
Once the launch configuration file has been made, you can run the Android application by either
selecting the Run icon from the Eclipse IDE toolbar or pressing the CTRL+F11 keys.
Before displaying the application output, emulator displays several boot screens. The first
Window’s title bar contains the port number of your computer (5554) on which the emulator is
running and the AVD name (demoAVD).
The second screen shows the Android logo, shows the loading phase and then displays the default
locked Home screen, as shown below.
To unlock the Home screen, either select the Menu button on the emulator, press the f2 key on
your computer, or drag the lock to the right .After the emulator is unlocked, the Home screen
appears, followed by the output of the application as shown in below
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 22
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
You can see that then applications title, HelloWorld, appears in the title bar of the emulator, and a
text message, Hello world, and is displays via the Text view control.
The output of the application confirms that the activity is running correctly in the emulator.
If you feel that the screen shown by the emulator is too big, you can reduce it to the actual size by
selecting the window, AVD manager option.
Android Device Manager Dialog box opens up, select demo AVD and click the start button. Select
the Scale to real size check box and then click the Launch button to start the emulator.
Don not close the emulator screen; let it stay active to save the emulator’s loading time for running
other applications.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 23
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
The Dalvik Virtual Machine (Dalvik VM):
While running Android applications, the android runtime provides the Dalvik virtual machine that
provides an environment to deploy and run Android applications.
Dalvik VM is the androids platform virtual machine written by Dan Bornstein. It is specifically
designed Virtual Machine for android and optimized for mobile devices with limited battery,
memory and computation capability.
When you run an application, the androids SDK access information in the XML files, converts it
into the java source code and place it the R.java file.
The java code in the R.java class file is compiled into the java byte code files, which, with the help
of a tool named dx, is converted into Dalvik byte code and stored in .dex format.
The Dalvik Executable format is optimized for efficient storage and low memory consumption.
Android applications are not deployed in dex code is bundled into an APK file.
The Application Package (APK) file:
The dex code that you get after converting the java file is bundled with other required data and
resources, including the manifest file AndroidMnaifest.xml into an application package file (.apk).
APK files represent a single application and install it on a mobile device or emulator. Each APK
installed on an Android device is given its own ID that remains unchanged for long as APK resides
on that device. APK must be signed with a certificate whose private key is held by its developer.
Using the Text View Control:
Now we learn to use the Text View control .You can assign text to the Text View in two ways:
1. Direct assignment to the Text View control as defined in the layout file activity_hello_
world_app.xml
2. Indirectly through the java Activity files Hello World App Activity.java.
Assigning the Text Directly in the layout File:
The text that you want to be displayed through the Text View control can be assigned to it in its
XML definition in the layout file activity_hello_world_app.xml.
From the package Explorer window, open activity_hello_world_app.xml by double-clicking it in
the res/layout folder. Modify activity_hello_world_app.xml to appear as 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">
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 24
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
tools:context=".HelloWorldAppActivity"/>
</RelativeLayout>
Only android:text statement is modified. Here, Hello World is assign to android:text attribute.
Lets run the application to see the output .The output displays the Text, “Hello World!, that you
assigned to the Text View control.
To make the message “Hello World!”Appear at the top-left control of the screen, remove the two
attributes android: layout_centerHorizontal and android from the android:layout_centerVertical
from the <Text View> tag in above code
Output of application shows text “Hello World” on top left corner of screen
Assigning Text through the Activity File:
To assign to the text view control through the Java Activity File HelloWorldAppActivity.java you
need to do the following two things:
1. Remove the text from XML definition- you need to do is to remove the text that was
assigned to the Text View control in the layout file activity_hello_world-app.xml. Open file
and remove the statement android: text=”Hello World!” and TextView control is blank.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 25
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
2. Assign an ID to the Text View control-To access the Text View control in the activity file; you
have to uniquely identify it by ID. It can done by android:id attribute in Text View tag
android:id=”@+id/message”
In above statement message is ID to the Text View control and plus sign in @+id/message means
that ID, message is created if it doesn’t already exists
<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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/message"
tools:context=".HelloWorldAppActivity"/>
</RelativeLayout>
After assign ID to TextView control, it will be accessible in Activity file. To assign text to
TextView control through HelloWorldAppActivity.java, modify it to appear as shown below
Package com.androidunleashed.helloworldapp;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class HelloWorldAppActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_world_app);
TextView mesg = (TextView) findViewById(R.id.message);
mesg.setText("HelloWorld !");
}
}
Control with the message ID in the layout file by using the findViewById method of the Activity
class and maps it to the TextView object,mesg.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 26
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Assigns the text HelloWorld! To mesg object and hence to the TextView control. We erased the
onCreateOptionsMenu() method because we are not dealing with menus.
On running the application, you see changes. Let’s assign a few more attributes to the TextView
control and change its height, width, color, style, background and alignment.
.
Applying Dimensions to Controls:
Dimensions are commonly used to specify the size and other properties for the controls and
layouts. The following units of measurements are used:
px (pixels)—Corresponds to the actual pixels on the screen.
in (inches)—Based on the actual size of the screen.
mm (millimetres)—Based on actual size of the screen.
pts (points)—Points are a fixed dimension—1/72 of an inch.
dip or dp (device-independent pixels)—Based on the physical density of the screen. This unit
is relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp to
pixel. Example “on a 240 dpi screen, 1dp is equal to 1.5 pixels.”
sp (scale independent pixels)—Similar to the dp unit, but also depends on the user’s font size
settings. Hence this unit is preferred while specifying font sizes.
Aligning Content with the Gravity Attribte:
The gravity attribute is used for aligning the content within a control or it’s container. To align text
of the TextView control to the center, you set the value of its android:gravity attribute to center.
Some of the valid values for the android:gravity attribute are shown in below
Value Description
Top Aligns the content to the top of the container.this value makes the text
align at the top of the TextView control.
Bottom Aligns the content to the bottom of the container.
Left Aligns the content to the left of the container.
Right Aligns the content to the right of the container.
center_horizontal Places the content at the horizontal center of it’s container’s width.
center_veritcal Places the content at the vertical center location of its container.
fill_horizontal Grows the horizontal size of the content to fill its container.
fill_veritcal Grows the vertical size of the container to fill its container.
Center Places the content at the center of its container
You can combine two or more values of any attribute using the ’|’ (pipe character).
For example, android:gravity=”center_horizontal | center_vertical”
If you want to apply the gravity attribute to any control through the java activity file, the java
method used for this purpose is setGravity().
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 27
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Commonly Used Attributes:
List of attributes commonly applied to configure the controls are shown below.
Attributes Java Method Description
Sets the width of the control equal to the
specified value. The value can be in any of
android:width setWidth()
the units of measurement in dimensions.
For example, android:width= ”150dp”.
Sets the height of the control equal to the
android:height setHeight() given value.
For example, android:height= ”200dp”.
Sets the text to display in the given control.
android:text setText()
For example, android:text= ”helloWorld!”.
Sets the color of the text. The color value is
specified in the form of hexadecimal RGB
values. Formats for specifying colors are
android:textColor setTextColor()
“#RGB”, “#ARGB”, ”#RRGGBB”, OR
”#AARRGGBB”.
For example, android:textColor=”#0F0”.
Sets the size of the text.
android:textSize setTextSize()
For example, android:textSize=”25dp”
If set, causes text that is longer than the
width of the container to be ellipsized
instead of breaking it in the middle. Valid
options are none, start, middle, end and
marquee. The options start, middle and end
android:ellipsize setEllipSize()
display dots at the beginning, middle and
end of the container’s width. The marquee
makes the text to scroll horizontally in
available width of container.
For example, android:ellipsize=”end”
Decides whether the control is supposed to
be a single-line input or multiple-line input.
Assigning the Boolean value true to this
android:singleLine setTransformationMethod()
attribute creates a single horizontal
scrollable line instead of multiple lines.
For example, andriod:singleline=”true”
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 28
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Attributes Java Method Description
Sets the background color of a control or
makes an image appear in the background of
the control. An image from the draw able
android:background setBackgroundResource() resource can be specified to appear in the
control’s background.
For example,
android:background=”#0000ff”
Applies a style to the text. The valid values
android:textStyle setTypeface() are bold, italic, bold italic.
For example, android:textstyle=”italic”
Sets the text to appear in a given font style.
The valid options are normal,sans,serif,and
android:typeface setTypeface()
monospace.
For example, android:typeface=”serif”
Let’s apply some of the attributes to the TextView control (in activity_hello_world_app.xml) of
the helloworldapp application, as shown below
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/message"
android:typeface="serif"
android:textColor="#0f0"
tools:context=".HelloWorldAppActivity"
android:textSize="25dp"
android:textStyle="italic"
android:gravity="center_horizontal" />
This code makes the text of the TextView control appear in serif font,green color,25dp size,italic
and at the horizontal center of the container
Let’s apply a few more attributes to the TextView control here:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/message"
tools:context=".HelloWorldAppActivity"
android:gravity="center"
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 29
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:height="200dp"
android:width="150dp"
android:typeface="serif"
android:textColor="#0F0"
android:textSize="25dp"
android:textStyle="bold"/>
This code makes the content of the TextView wrap move to the next line if the width assigned to it
is insufficient.
The TextView control is assigned the height and width of 200dp and 150dp and its text is set to
appear at the center of its assigned size.
The text appears in serif font, green color, 25dp font size and bold. The text in the TextView
appears as shown below.
Using the Android Emulator:
The Android emulator is used for testing and debugging applications before they are loaded onto a
real handset. The Android emulator is integrated into Eclipse through the ADT plug-in.
Limitations of the Android Emulator:
The android emulator is useful to test android applications for compatibility with devices of
different configurations.
it is a piece of software and not an actual device has several limitations:
1. Emulators no doubt help in knowing how an application may operate within a given
environment, but they still don’t provide the actual environment like memory, CPU or other
physical limitations to application.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 30
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
2. Emulators just simulate certain handset behaviour. Features such as GPS, Sensors, Battery,
Power settings and network connectivity can be easily simulated on a computer.
3. SMS messages are also simulated and do not use a real network.
4. Phone calls cannot be placed or received but are simulated.
5. No support for device attached headphones is available.
6. Peripherals such as camera/video capture are not fully functional.
7. No USB or Bluetooth support is available.
You can use the mouse and keyboard to interact with the emulator when it is running.You can use
your computer keyboard to input text into UI controls and to execute specific emulator commands.
Some of the most commonly used commands are
Back[ESC button] End[F4]
Call[F3] Volume Up[KEYPAD_PLUS,Ctrl-F5]
Volume down[KEYPAD_MINUS,Ctrl-F6]
Switching orientations[KEYPAD_7,Ctrl-F11/KEYPAD_9,Ctrl-F12]
You can also interact with an emulator from within the DDMS tool. Eclipse IDE provides three
perspectives to work
The Java Perspective :-
It’s the default perspective in Eclipse where you spend most of the time. It shows the
panes where you can write code and navigate around the project.
The Debug perspective :-
It enables application debugging. You can set breakpoints, step through the code, view
LogCat logging information, threads and so on.
The Dalvik Debug Monitor Service (DDMS) perspective :-
It enables you to monitor and manipulate emulator and device status. It also provides
screen capture and simulates incoming phone calls, SMS sending and GPS coordinates.
You can switch between perspectives by choosing appropriate icon in top right corner of Eclipse
environment
The Android Debug Bridge (ADB):
The android debug bridge (ADB) is a client-server program that is part of the android SDK. It is
used to communicate with, control and manage the android device and emulator.
It consists of three components:
CLIENT --Runs on a computer machine. It can be invoked from the command prompt using
the adb command.
DAEMON --Runs as a background process in either an emulator instances or in device itself.
SERVER --Runs in a computer machine in the background. It manages the communication
between the client and the daemon.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 31
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
When you install the android SDK, the Android Debug Bridge is also automatically installed along
with it. When ADB is activating, you can issue adb commands to interact with one or more
emulator instances.
Using the shell command, you can perform several tasks such as listing existing applications,
deleting applications, and querying or modifying SQLite database on device.
To access ADB through windows, open the command prompt and navigate to the folder where
adb.exe is located by using the cd command.
By default, adb.exe is installed in C:\program files(x86)\Android-sdk\platform-tools. After
finding adb, you can issue the following commands to interact with the device or emulator:
adb devices --- Displays the list of devices attached to the computer currently on your
computer, emulator-5554.
adb push --- Copies files from your computer to the device /emulator.
Syntax :- adb push source destination
Where source to the file along with its path that you want to copy, an
destination refers to the device or emulator where you want to copy the file.
adb pull --- Copies files from the device/emulator to your computer.
Syntax:- adb pull source(destination)
adb shell --- Display the shell prompt where can issue Unix commands. You can see the
names of different files and folders of the emulator after issue ls a command.
You can the commands to list, rename, and delete applications from the emulator For example, to
delete the file song 1.mp3 that you pushed into the emulator, you issue the rm command. To leave
Shell; Press Ctrl+d.
adb install --- Install an application from your computer to the device/emulator.
Syntax:- adb install appname.apk
This Code C:\program Files(x860\Android\android-sdk\platform-tools>adb install D:\ androidun
leashed\loginApp.apk. Installs the application package file loginApp.apk into the emulator.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 32
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Launching Android application on hand set:
To load application on real hand set, you need to plug handset into your computer, using USB
cable.
You first confirm whether configurations for debugging your application are correct or not and
launch application as shown below
1. In eclipse ,choose Run , Debug configuration option
2. Select configuration Helloworld_cofiguration. which you created for helloworld application
3. Select target tab, set deployment target selection Mode to Manual. Manual option allows us to
choose device or AVD to connect to when using this configuration
4. Apply changes to configuration file by clicking Apply button
5. Plug an Android device into computer, using USB cable
6. Select Run, Debug in Eclipse or Press F11 key. Dialog box appears, showing all available
configurations for running and debugging your application. Physical device connected to
computer are also listed. Double click running android device. Eclipse now installs android
application on handset, attaches debugger and runs the application
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 33
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
UNIT - II
BASIC WIDGETS
Understanding Role of Android Application Components:
Let’s start by creating an application that prompts the user to enter name and display welcome
message in return.
To create application, open eclipse and choose, file, new android application project or click
android project creator icon on eclipse toolbar.
In the Application Name box, enter the name of the Android project. Let’s name the application
WelcomeMsg. The project Name is automatically assigned, which is the same as the application
name by default. The Package Name is com.androidunleashed.welcomemsg.
From the Build SDK drop-down, select Android 4.1 (API 16) as the target platform as we expect it
to be the version commonly used by your target audience.
Select API 8: Android 2.2 (Froyo) from the Minimum Required SDK drop-down to indicate that
the application requires at least API level 8 to run.
Select Create project in Workspace check box and Create custom launcher icon check box for new
project. Click the Next button to move to the next dialog box.
Next dialog is Configure Launcher Icon, which is meant for configuring the icon for the
application. Keeping all default options in the dialog box, click the Next button to move further.
Next dialog prompts us to select whether we want to create an activity. To create BlankActiity,
Select Create Activity check box and the Blank Acitivity option from the list and then click next.
The next dialog asks us to enter information about the newly created activity. Name the activity
WelcomeMsgActivity.
The layout filename and title name automatically change to reflect the newly assigned activity
name. Click the Finish button after supplying the required information.
The application is created by ADT, along with all the necessary files.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 1
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Understanding the Utility of Android API:
The android platform provides a framework API that applications can use to interact with the
underlying Android system. The framework API consists of a core set of packages and classes;
XML elements for declaring layouts, resources, and so on; a manifest file to configure
applications; intents; and much more.
Framework API is specified through an integer called API level, and each Android platform
version supports exactly one API level, although backward compatibility is there; that is, earlier
API levels are supported.
The initial release of the Android platform provided API Level 1, and subsequent releases have
incremented the API level. List of API levels shown below
Version Number API Level Code Name
Android 4.1 16 Jelly bean
Android 4.0.3 15 Ice cream Sandwich
Android 4.0 14 Ice cream Sandwich
Android 3.2 13 Honey comb
Android 3.1 12 Honey comb
Android 3.0 11 Honey comb
Android 2.3.3 10 Ginger bread
Android 2.3.1 9 Ginger bread
Android 2.2 8 Froyo
Android 2.1 7 Eclair
Android 2.0.1 6 Eclair
Android 2.0 5 Eclair
Android 1.6 4 Donut
Android 1.5 3 Cup cake
Android 1.1 2
Android 1.0 1
Remember that to enable applications to run on a maximum number of platforms, you can set the
applications to target the lowest platform, Android 1.0.
Because of backward compatibility, the application that supports the Android 1.0 platform can
easily run on all the devices, even on devices with the Android 4.0 platform. Opposite is not true.
After creating the new Android application by name, WelcomeMsg, the ADT creates a
WelcomeMsg directory in the default Eclipse workspace for the project.
It also creates subdirectories for keeping source files, compiled or generated files, resource files,
and so on.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 2
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Several files, such as AndroidManifest.xml and project.properties are also automatically created to
make the job of configuring the Android application.
You can have a look at the files and directories created by ADT if you expand the project tree in
the Package Explorer window.
Overview of the Android Project Files:
The list below is just an overview of the files and directories.
1. /src folder: The folder that contains the entire Java source file of the application. The folder
contains a directory structure corresponding to the package name supplied in the application.
The folder contains the project’s default package: com.androidunleashed.welcomemsg. On
expanding the package, you find the Activity of the application, the WelcomeMsgActivity.java
file, within it.
2. /src/com.androidunleashed.welcomemsg: Refers to the package name of the application. To
avoid any collision among the class names, variable names, and so on from other Android
application. each application has to be packed in a unique container.
3. /src/com.androidleashed.welcomemsg/WelcomeMsgActivity.java: The default Activity files
of the application. Recall that each application has at least one Activity that acts as the main
entry point to the application. The activity file is automatically defined as the default launch
Activity in the Android Manifest file.
4. /gen folder: Contains Java files generated by ADT
on compiling the application. The gen folder will
come into existence after compiling the application
for the first time. The folder contains an R.java file
that contains references for all the resources defined
in the res directory. It also contains a BuildCon-
fig.java file that is used to run code only in debug
mode.
5. /gen/com.androidunleashed.welcomemsg/R.java:
All the layout and other resource information that is
coded in the XML files is converted into Java source
code and placed in the R.java file. The R.java file is
compiled into the java byte code files and then
converted into .dex format. You should never edit
this file by hand.
6. Android SDK jar file: The jar file for the target
platform.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 3
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
7. /assets folder: The assets folder is empty by default. It stores raw asset files that may be
required in the application. It may contain fonts, external JAR files, and so on to be used in the
application. The assets folder is like a resource folder where uncompiled resources of the
project are kept.
8. /bin folder: The folder that stores the compiled version of the application.
9. /res folder: The folder where all application resources (images, layout files, and string files)
are kept. Create a respective resource in the res folder is better than hard coding image or
string. You can change image or string or any other resource any time without disturbing code.
Each resource is assigned a unique resource ID, which automatically appears in the R.java file.
To categorize and arrange the resources, three subdirectories are created by default: drawable,
layout and values.
10. /res/drawable-xhdpi, /res/drawable/hdpi, /res/drawable-mdpi, /res/drawable-ldpi: applica-
tion’s icon and graphic resources are kept in these folders. Because devices have screens of
different densities, the graphics of different resolutions are kept in these folders .Usually
graphics of 320dpi, 240dpi, 160dpi and 120dpi are stored in the res/drawable-xhdpi, res/
drawable-hdpi/, res/drawable-mdpi , and res/drawable-ldpi folders, respectively. Application
picks up the graphic based on density of device.
11. /res/layout: Stores the layout file(s) in XML format.
12. /res/values: Stores all the values resources include many types such as string resource ,
dimension resource and color resource.
13. /res/layout/activity_welcome_msg.xml: The file used by WelcomeMsgActivity to draw views
on the screen. The views or controls are laid in the specified layout.
14. AndroidManifest.xml: The central configuration files for the application.
15. Proguard.cfg: Defines how proGuard optimizes the application code. ProGuard is a tool that
removes unused code from the Android application and optimizes it, which increases
performance.
16. Project.properties: Build file used by Eclipse and the Android ADT plug-in. It contains
project settings such as the build target. You can use this file to change various properties of
the project with editors available in Eclipse.
Other folders include bin, libs and reference libraries are part of application. The bin folder is
hidden. The libs and referenced libraries folders don’t appear until a third party library and
reference are added to the project.
The default content of the Activity file WelcomeMsgActivity. java is shown below
Package com.androidunleashed.welcomemsg;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 4
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
public class WelcomeMsgActivity extends Activity {
@Override
Public void onCreate(Bundle savedInstanceState) {
Super.onCreate(savedInstanceState);
setContentview(R.layout.activity_welcome_msg);
}
@Overrride
Public Boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.activity_welcome_msg, menu);
return true;
}
}
Understanding Activities:
Every unique screen user interacts with in an application is displayed through an Activity. Simple
application may consist of just one Activity, where as large application contains several Activities.
A stack of Activities is maintained while running an application and activity at top of the stack is
one currently being displayed. When the back button is pressed, the Activity is popped from stack.
The transition from one Activity to another is accomplished through the use of asynchronous
messages called intents. Intents can be use to pass data from one Activity to another.
All the activities in the application must be defined in the Application’s manifests life. Each
Activity in an Android application is either a direct subclass of the Activity base class or a subclass
of an Activity subclass.
Understanding Android Activity Life Cycle:
The Android Activity life cycle defines the states
or events that an Activity goes through from the
time it is created until it finishes running.
Activity monitors and reacts to these events by
executing methods that override Activity class
for each event.
Lists the methods executed during the different
events that occur during an android Activity life
cycle shown below.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 5
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
METHOD DESCRIPTION
The method called when the Activity is first created. It initializes the value
onCreate() and is used to create the views of the application, open persistent data files
required by the Activity and so on.
The method called just before the Activity becomes visible on the screen. An
Activity can be either in a foreground or background state. When an Activity
onStart()
switches to the background state, the onStop() method is executed and when
it switches to foreground, the onResume() method is invoked.
The method called whenever the Activity becomes the foreground Activity,
whether it is right after the execution of the onStart() method or when some
onResume() other foreground Activity exits and the Activity appears at the top of the
Activity stack. A foreground Activity interacts with the user, i.e. receives
keyboard and touch inputs and generates the response.
The method called when the Activity is stopped and no longer is visible in the
foreground and some other Activity is switched to the foreground. This
onPause() method contains commands to minimize consumption of resources and to
store the Activity state, which will be used when the Activity resumes to the
foreground.
The method called when the Activity is no longer visible, either because
onStop() another Activity is switched to the foreground or because the Activity is
being destroyed.
The method called used when the Activity is completed and is about to get
onDestroy() destroyed. The system may simply terminate the process. You can use this
method to release the resources consumed by the Activity.
All the activities of an application, permission and intents are defined through the XML-structured
manifest file AndroidManifest.xml. in this file all the different components of the application are
defined.
Role of the Android Manifest File:
The configuration file AndroidManifest.xml is created by ADT when creating a new Android
project and is kept in the project’s root directory.
Xml file that defines the overall structure and information about the application and it also contains
the information required in building and packaging the application for installing and deploying it
on an Android device or the emulator.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 6
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
It defines meta data of application such as its icons and label. Manifest file for the application that
you just created shown below.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com. androidunleashed.welcomemsg "
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style.AppTheme">
<activity android:name=".WelcomeMsgActivity"
android:label= "@string/title_activity_welcome_msg”>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The <manifest> tag, is the root element of this XML document and contains several attributes:
1. Android: Identifies the andriod namespace used to provide several system attributes used
within the application.
2. package: Its value is set to the application's Java Package. The name of the application
package acts as the unique identifier for the application in the Android device.
3. versionCode/versionName: The Version Code attribute is used to define the current
application version. The versionName attribute is used to specify a version number that is
displayed to users.
4. <uses-sdk>: This tag is optional and is used to specify the Maximum, Minimum and preferred
API level required for the application to operate. Three attributes are used with this tag as
follows:
android:minSDKversion: Used to specify the minimum API level required for this
application to run. The default is"1". Minimum API level required by the application is 15.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 7
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
the application cannot run on an API level lower than the one specified attribute
andriod:minSDKVersion="15".
android:targetSDKversion: Used to specify the preferred API level on which the
application is designed to run.
android:maxSDKversion: Used to specify the maximum API level supportable by the
application, the application cannot run on an API level higher than the one specified
attribute.
5. <application> tag: which is the parent of application controls tags. @string and @drawable
refer to the strings and drawable resources, respectively.
6. <activity> tag: which describes an Activity component. This tag's name attribute identifies a
class that is an Activity, welcomemsactivity. It relative to com.androidunleashed.welcomemsg
package.
7. <intent-filter>: The intents are used to interact with the applications and services. By default,
the intent specifies the action as MAIN and the category as LAUNCHER; that is, it makes
application launcher to launch when the application starts.
The following are some of the most commonly used tags:
1. <service> tags: Used for declaring service. service refer to the process that run in the
background without a user interface.
2. <receiver> tags: Used for declaring broadcast receivers. Boardcast receivers are used to listen
and respond to broadcast announcements. An application can have any number of broadcast
receivers. A broadcast receiver responds by taking a specific action.
3. <provider> tags: Used for declaring content providers. They help in handling, storing, and
sharing data such as audio, images, video and contact lists with other applications..
4. <uses-permission> tags: Used for declaring the permission that the application needs.
Example:
<uses-permission android:name="android.permission.CAMERA"/>:
Used for the application that needs to use the camera.
<uses-permission android:name="android.permission.INTERNET"/>:
Used for the application that needs to access the internet.
Using the Manifest Editor:
To manipulate androidmanifest.xml file use of the manifest editor in eclipse, right click the
androidmanifest.xml file in the package explorer window, and select open with android manifest
editor.
Android Manifest overview screen shown below
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 8
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Screen provides user-friendly interface to configure application, enabling you to set application
version information and root-level manifest nodes, including uses-sdk and uses-permission.
It provides shortcut links to the application, permissions, instrumentation and raw xml screens.
Creating the User Interface:
There are three approaches to creating user interface in android. You can create user interface
entirely in java code or entirely in XML or in both.
The XML file in which you create the user interface is activity_welcome_msg.xml found in the
res/layout folder. The default layout in which the controls or views are usually arranged is
RelativeLayout. it 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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@srting/hello_world"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
tools:context=".WelcomeMsgActivity"/>
</RelativeLayout>
You want to prompt the user to enter a name,and in return the application displays a welcome
message along with the entered name.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 9
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
To achieve above requirement you change activity_welcome_msg_.xml shown below
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter your name:"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Click Me"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>
In the preceding XML file, four controls are used: two TextViews, one EditText and one Button
Control. The first TextView prompts the user to enter a name by displaying the message Enter
your name: and the second TextView is used to display the Welcome message to the user.
When the user selects the Button, control will display welcome message through the second
TextView control.
The EditText, Button, and one of the TextView controls are assigned the IDs user_name, click_btn
and response, respectively. These IDs are used to access these controls in the java Activity file.
Commonly Used Layouts and Controls:
The Views or the controls that we want to display in an application are arranged in an order or
sequence by placing them in the desired layout.
Some of layouts as follows:
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 10
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
1. LinearLayout: In this layout, all elements are arranged in a descending column from top to
bottom or left to right. Each element contains properties to specify how much of the screen
space it will consume.
2. RelativeLayout: In this layout, each child elements is laid out in relation to other child
elements. That is, child elements appear in the relation to the parent.
3. AbsoluteLayout: In this layout, each child is given a specific location within the bounds of the
parent layout object. This layout is not suitable for devices with different screen sizes.
4. FrameLayout: This is a layout used to display a single view. Views added to this are always
placed at the top left of the layout. Any other view that is added to the FrameLayout overlaps
the previous view.
5. TableLayout: In this layout, the screen is assumed to be divided into table and rows, and each
of the child elements is arranged in a specific row and column.
6. GridLayout: In this layout, child views are arranged in a grid format (in the rows and columns
pattern). The views can be placed at the specified row and column location. Also, more than
one view can be placed at the given row and column position.
The following list highlights some of the controls commonly used in Android applications:
1. Textview: A read-only text label. It supports multiline display, string formatting automatic
word wrapping.
2. EditText: An editable text box that also accepts multiline entry and word-wrapping.
3. ListView: A ViewGroup that creates and manages a vertical list of views, displaying them
as rows within the list.
4. Spinner: A TextView and an associated list of items that allows us to select an item from
the list to display in the text box.
5. Button: A standard command button.
6. CheckBox: A button allowing a user to select (check) or unselect (uncheck).
7. RadioButton: A mutually exclusive button, which when selected, unselects all other buttons
in the group.
Event Handling:
In our sample application, you want the user to enter a name in the EditText control. After the user
has entered the name and clicks the Button control, a welcome message displays on the screen.
The action of clicking a Button, pressing the Enter Key, or performing any action on any control is
considered an event. The action to be taken when the event occurs is called event handling.
To handle an event, you use the listeners that wait for an event occurrence. Event listener is an
interface in the view class that contains single callback method, called an event occurrence.
An instance of the implementation is passed to the respective control through the
setOnClickListner( ) method.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 11
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Event handling should be three ways:
1. Creating an anonymous inner class
2. Implementing the OnClickListener interface
3. Declaring the event handler in the XML definition of the control
Creating an Anonymous Inner Class:
In this method of event handling, an anonymous class is defined with an OnClickListener
interface, and an onClick(View v) method is implemented in it.
The anonymous inner class is passed to the listener through the setOnClickListener( ) method. To
implement the concept of anonymous inner class for event handling, the java activity file
WelcomeMsgActivity.java is modified to appear as shown below.
Package com.androidunleashed.welcomemsg;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
public class WelcomeMsgActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg);
Button b=(Button)this.findViewById(R.id.click_btn);
b.setOnClickListener(new Button.OnClickListener( ){
public void onClick(View v) {
TextView resp=(TextView) findViewById(R.id.response);
EditText name=(EditText) findViewById(R.id.user_name);
String str="welcome "+name.getText( ).toString( )+" ! ";
resp.setText(str);
}
});
}
}
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 12
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Listener is implemented inline through an anonymous class with an onClickListener interface. A
callback method onClick(View v) is implemented in the class, and, finally, the anonymous class is
associated with the Button object b.
whenever the Button control is clicked in the application , the onClick( ) method, you fetch the
TextView and EditText controls defined in the layout file with the ID’s response and user_name,
and then map them to the TextView and EditText objects resp and name, respectively.
The name entered by the user is prefixed with a Welcome message, is assigned to a string object,
str. Finally, the str object is assigned to The TextVew object, resp, to display the Welcome
message, along with the user’s name on the screen.
Running the Application:
To run the application, you create an Eclipse launch configuration. If you run the application
without creating a launch configuration, you see the Run as dialog box shown below.
Choose Android Application, and a launch configuration is
automatically created.
The ADT compiles the application and then deploys it to the
emulator with the default launch configuration.
The Android emulator is loaded showing the output of the
application. You can see in the emulator that a prompt
message Enter your name: appears via the TextView Control.
A blank text box appears via the EditText Control where you
will enter name and button appears via Button Control.
After you enter the user name Kelly and select the Click Me button, a welcome message,
Welcome Kelly!, appears via the TextView Control.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 13
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Activity Implementing the OnClickListener Interface:
In this method of event handling, the Activity class implements the onClickListener interface,
which requires us to implement the onClick() method in this class.
The onClick() method is declared inside the class and the listener is set by passing a reference to
the class by the following statement:b.setOnClikListener(this).
To implement OnClickListener interface, the activity file WelcomeMsgAcivity.java is modified to
appear as shown below.
package com.androidunleashed.welcomemsg;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class WelcomeMsgActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg);
Button b = (Button) this.findViewById(R.id.click_btn);
b.setOnClickListener(this);
}
public void onClick(View v) {
TextView resp=(TextView) findViewById(R.id.response);
EditText name=(EditText) findViewById(R.id.user_name);
String str="welcome "+name.getText( ).toString( )+" ! ";
resp.setText(str);
}
}
This code locates the Button Control that you created in the activity_welcome-msg.xml file (with
the ID click_btn), assigns it to the instance b, and attaches an event listener to it.
When event occurs via a button click, the onClick() method is executed. TextView and EditText
controls of activity_Welcome_msg.xml are located and accessed via the resp and name objects.
The username entered in the EditText control is fetched and displayed along with a welcome
messasge via the TextView Control.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 14
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Declaring the Event Handler in the XML Control Definition
Since Android SDK 1.6, another way to set up a click handler for the Button Controls is there.In
the XML definition of a Button in the layout file activity_welcome_msg.xml,you can add an
android:onClick attribute.
This attribute is used to represent the method you want to execute when a click event occurs via
the Button Control.
android:onClick="dispMessage"
All you need is to define the dispMessage () in the Activity class to perform the desired action.
Remember, to try out this method of event handling, you need to modify the layout file
activity_welcome_msg.xml of the application is as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter your name:"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Click Me"
android:onClick="dispMessage"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>
The attribute android:onClick means that the dispMessage() method must be invoked when the
button is clicked. You can declare the same event handler for several controls.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 15
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
In the Java Activity file WelcomeMsgActivity.java, the method dispMessage() is defined. This
method performs the task of accessing the name entered in the EditText control and displaying a
welcome message along with the entered name.
Add method dispMessage(), Activity file WelcomeMsgActivity.java appears as shown in below.
package com.androidunleashed.welcomemsg;.
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
public class WelcomeMsgActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg); }
public void dispMessage(View v){
TextView resp=(TextView) findViewById(R.id.response);
EditText name=(EditText) findViewById(R.id.user_name);
String str = "Welcome " + name.getText().toString() + " ! ";
resp.setText(str);
}
}
In the dispMessage() method , TextView and EditText controls with the Ids response and
user_name are accessed from the layout file, activity-welcome_msg.xml and mapped to the
TextView and objects resp and name, respectively.
The username entered in EditText control is accessed through the name object (EditText control)
and is designed to the resp object (TextView Control) along with welcome message for display.
Define same event handler method more than one button control with help of view object. In event
handler, the getid() method of the view object can be used to discover the button from which the
event has occurred and an appropriate action can be taken, as shown below:
public void dispMessage (view v) {
if (v.getId()==R.id.id1) { }
if (v.getId()==R.id.id2) { }
......
}
id1 and id2 are the IDs of the button controls that declare the same event handler.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 16
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Displaying Messages through Toast:
A Toast is a transient message that automatically disappears after a while without user interaction.
It is used to inform the user about happenings that are not very important
A Toast is created by calling the static method, makeText (), of the Toast class. The syntax of the
makeText () method is shown below:
Toast.makeText (Activity_context, string_to_display, duration)
The method needs the Activity (Context) String to display, as well as the duration for which the
message is displayed on the screen. You can also supply the ID of the String resource that you
want to display.
The duration is expressed in the form of constants, such as Toast.LENGTH_SHORT or
Toast.LENGTH_LONG, to determine the duration for which the string’s message remains on the
screen.
You call the show() method on the returned Toast instance to display the containing string or
message.
To display the welcome message through Toast, modify the java activity file WelcomeMsg
Activity.java as shown below.
package com.androidunleashed.Welcomemsg;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.view.View;
import android.widget.Toast;
public class WelcomeMsgActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg);
}
public void dispMessage(View v) {
EditText name=(EditText) findViewById(R.id.user_name);
String str="welcome "+name.getText( ).toString( )+" ! ";
Toast.makeText (WelcomeMsgActivity.this, str, Toast.LENGTH_SHORT) .show () ;
}
}
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 17
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
You can see that a String object, str, is defined, which contains a welcome message and the name
entered by the user in the EditText control with the ID user_name.
The text in the string object, str, is displayed via Toast, as shown in below. Toast is transient, it is
not visible for an extensive period, and you don’t receive any confirmation that the user actually
saw it.
Therefore, we continue to use the TextView control in Android application to display information
to the user.
Creating and String an Activity:
The structure that is used to start, stop, and transaction between Activities within an application is
called Intent.
Describing Operations through Intent:
Intent is a data structure; it consists of an action that the application needs to perform, data to
operate on, and other information helpful in executing the operation.
Intent can be explicit or implicit as follows:
Explicit Intent-In an explicit intent, you specify the Activity required to respond to the intent;
that is, you explicitly designate the target components. Because your application, an explicit
intent is limited to be used within an application
Implicit Intent-In an implicit intent you just declare intent and leave it to the platform to find
an Activity that can respond to the intent. It is the job of the Android platform to search for the
most suitable component to handle the implicit intent.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 18
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Method Used to start an activity:
The method used to start an activity is startActivity(). First create an implicit or explicit intent
object and pass it to the startActivity() method in the format here:
startActivity (my_intent) ;
Where my_intent passed as a parameter to startActivity(). The startActivity() method find and
starts the single Activity that best matches the given intent.
To explicit specify the Activity that you want to start through an intent, create a new intent
specifying the current application context and class name of the activity you want to launch and
pass this Intent to the startActivity () method,as shown here:
startActivity (new Intent (this, welcome.class));
If startActivity() is unable to find the specified activity, an android.content.ActivityNotFound
Exception is thrown.
Let’s explore the concept, You create an application similar to the WelcomeMsg application but
with the following two differences:
Instead of using the default Activity automatically created by the ADT, you create your own
Activity in this application.
You create and use your own layout file instead of the default layout file.
Launch Eclipse and create a new Android Project called welcomeApp with the following settings:
Select Android 4.1 as the Target Platform.
Let the application name be the default, which is welcomeApp.
Let the package name be com.androidunleashed.welcomeapp.
Let the Activity name be the default, which is welcomeAppActivity.
Creating your own Layout File:
To create a new layout file, from the Package Explorer window, right click the res/layout folder
and select the New, Android XML File option.
A dialog box appears asking for information about the new Android XML File. In the File text
box, enter the filename as welcome. Select the option linear layout from the Root Element and
finally, select the Finish button.
The layout file, welcome.xml, is created in the res/layout folder. The initial content of the file is
shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 19
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
add two TextView controls, an EditText and a Button control, to the layout file. After you add
these controls, the contents of the welcome.xml file will be as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter your name:"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Click Me"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>
Creating a New Activity:
You know that an Activity file is in the form of a java file. So, you need to add a java file to the
package com.androidunleashed.welcomeapp that’s inside the src folder of the application.
To create an Activity, right-click the package com.androidunleashed.welcomeapp and select the
New, class option.
A New Java Class dialog box appears, requesting you to enter the name of the Java file. Finally,
Select the Finish button to create the Java file.
The Activity welcome.java is added to the package with the default content, as shown here:
Package.com.androidunleashed.welcomeapp;
Public class Welcome {
}
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 20
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Let’s add some action to the Activity file. Recall that this application is similar to the
WelcomeMsg application. it prompts the user to enter a name and prints a welcome message when
the Button control is selected.
Package com.androidunleashed.welcomeapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
public class Welcome extends Activity{
@override
Protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.welcome);
Button b= (Button)this.findViewById (R.id.click_btn);
b.setOnClickListener (new Button.OnClickListener(){
public void onClick(View v){
TextView resp= (TextView)findViewById(R.id.response);
EditText name= (EditText)findViewById(R.id.user_name);
String str= “welcome “+name.getText().toString()+” !”;
resp.setText(str);
}
});
}
}
Registering the New Activity:
Only the components declared in the application’s manifest file AndroidManifest.xml are visible to
Android and hence can be used to run the application.
So, new Activity Welcome.java must be declared in the AndroidManifest.xml file to make it
visible to Android and start it.after adding new activity AndroidManifest.xml file is modified as
shown below
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com. androidunleashed.welcomemsg "
android:versionCode="1"
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 21
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style.AppTheme">
<activity android:name=".WelcomeMsgActivity"
android:label= "@string/title_activity_welcome_app”>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Welcome" android:label="@string/app_name"/>
</application>
</manifest>
Starting the Activity:
After registering the Activity welcome.java in the AndroidManifest.xml file, you can now start it
by using the startActivity() method.
This startActivity() method is the default Activity file WelcomeAppActivity.java for start, after
adding the startActivity() method, appears as shown below.
package com.androidunleashed.welcomeapp;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
public class WelcomeAppActivity extends Activity{
@override
Public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_app);
startActivity(new Intent(this, Welcome.class));
}
}
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 22
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
The startActivity() method creates an explicit intent, which explicitly specifies that the Activity
file Welcome.java is to be run at the start.
When the application is run, you see the same output as that of the WelcomeMsg application.
Using the EditText Control:
The EditText control is a subclass of TextView and is used for getting input from the user. You
can use several attributes to configure the EditText control to suit your requirements.
The default behaviour of EditText control to remain on a single line only and let the text scroll to
the left.
You can also hide the characters typed by the user for security purposes, that is, convert the
characters into dots, which you usually see while typing passwords.
Example:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"
android:text="Enter your name:"
android:singleLine="false"/>
The preceding example sets the EditText control to expand to multiple lines when the user types
beyond the width of the control. The control displays the hint text Enter your name, which is
automatically erased as the user types data.
Attributes Used to Configure the EditText Control:
The following is a list of attributes that can be used to configure the EditText control:
1. android: layout_width :
Used to set the width of the EditText control. The two valid values are wrap_content and
match_parent. The value wrap_content sets the width of the EditText control to accept only a
single character. When the user types text, the width of the EditText control automatically
increases to accommodate the new content. Also, the cursor moves to the next line when the
boundary of the container is reached.
No text scrolling takes place unless the android: scrollHorizontally attribute is set to “true”.
In this case, instead of moving to the next line, the text scrolls left to accommodate the newly
typed content.
If the value of the android: layout_width attribute is set to match_parent, the width of the
EditText control is set equal to the width of its container. When the user types the text
beyond the available width, the cursor moves to the next line.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 23
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
2. android: layout_height :
Used to set the height of the EditText control. Valid values are wrap_content and
match_parent. When the value wrap_content is assigned to the control, the height of the
EditText control increases when typing text beyond the width of the control.
If the value match_parent is assigned to the control, text expands the height of the control to
fill up the height of the container.
3. android: singleLine
When set to true, forces the EditText control to remain on a single line. That is, on reaching
the end of the available width, the text that is typed in scrolls to the left.
If the value is set to false, the cursor moves to the next line when the end of the available
width of the control is reached.
4. android: hint
Displays helpful text in the EditText control to guide user entry. The text automatically
disappears when the user enters data. For example, android: hint=”Enter your name”.
5. android: lines
Sets the height of the EditText control to accommodate the specified number of lines. For
example, android: lines=”5”. Typing text beyond the fifth line causes the text to scroll up .
6. android: textSize
Sets the size of the text typed in the EditText control. You can specify the size in any of the
following units of measurement: px, in, mm, pts, dip, and sp. For example, android:
textSize=”15px”.
7. android: autoText
When set to true enables the EditText control to correct common spelling mistakes.
8. android: capitalize
Automatically converts typed text into capital letters. The valid values are none, characters,
words and sentences.
The value none does not capitalize anything. The value character capitalizes every character.
The value words capitalize the first character of every word. The value sentences capitalize
the first character of the first word of each sentence.
9. android: password
When set to true, the attribute converts the typed characters into dots to hide entered text.
10. android: minWidth
Used to specify the minimum width of the control.
11. android: maxWidth
Used to specify the maximum width of the control. Text typed beyond the maximum width
scrolls if the android: scrollHorizontally attribute is set to true; otherwise, it moves onto the
next line.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 24
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
12. android: minHeight
Used to specify the minimum height of the control.
13. android: maxHeight
Used to specify the maximum height of the control.
14. android: scrollHorizontally
When set to true, makes the text scroll horizontally if typed beyond the specified width of the
control.
15. android: inputType
Specifies the type of data that will be typed in the EditText control. This attribute configures
the onscreen keyboard too.
There are many possible values that include number, phone, text, textCapCharacter,
textCapWords, textEmailAddress, datetime, date,time,textAutoCorrect,textMultiLine and
textPassword. The following figure shows how the onscreen keyboard changes when the
values number, phone, text, textCapCharacter and textEmailAddress. Single attribute actually
replaces many attributes as android: password, android: singleLine, android: numeric,
android: phoneNumber, android:capitalize and android:autoText.
Adding an Event Listener to the EditText Control:
You learn how to add an event listener to the EditText control that checks for the occurrence of an
event in the EditText control and executes the callback method.
In this application, an EditText control is displayed on the screen asking the user to enter a name.
After the user enters a name and presses the Enter key, a welcome message displays via the
TextView control.
First launch Eclipse and create a new Android project called EditTextApp, and modify
activity_edit_text_app.xml as shown below
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 25
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"
android:text="Enter your name:"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>
You can see that the layout contains two controls: EditText for getting the name from the user and
TextView for displaying a welcome message. The EditText and TextView controls are assigned
the user_name and response IDS, respectively.
To add an action, that is, to display the welcome message when the user presses the Enter key after
entering a name, we need to write code in the Activity file EditTextAppActivity.java shown below
Package.com.androidunleashed.edittextapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.KeyEvent;
public class EditTextAppActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_text_app);
final TextView resp= (TextView) this.findViewById (R.id.response);
final EditText username=(EditText) findViewById(R.id.user_name);
username.setOnKeyListener(new OnKeyListener() {
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 26
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
public boolean onKey(View v, int keyCode, KeyEvent event) {
if((event.getAction()== KeyEvent.ACTION_UP) &&
(keyCode==(KeyEvent.KEYCODE_ENTER))){
resp.setText("Welcome "+username.getText()+"!");
return true;
}
return false;
}
});
}
}
EditText control from the layout is captured and mapped to the username EditTextobject.To
display the welcome message to the user, TheTextView control with the response ID is captured
from the layout and assigned to the TextView object resp.
An event listener, OnKeyListener, is added to the EditText,object username so that the callback
method onkey() is invoked whenever a key is pressed. The onkey() method is implemented, it
checks whether the enter key is pressed.
When the enter key is pressed, welcome message is displayed to the user through the TextView
object, resp. The onkey() method is set to return false until the enter key is pressed. The onkey()
method is set to return true when the enter key is pressed by the user.
In output can see the hint text Enter your name in the Edit Text control. After the user has entered
name and pressed the enter key, the username and the welcome message appear, as shown below
Choosing Options with ChekBox:
A checkbox control has two states: checked and unchecked. When the checkbox is selected, it
toggles its state from checked to unchecked and vice versa
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 27
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
.A checkbox is created via an instance of android.widget.CheckBox. in java, the following
methods can be used with CheckBox controls:
1. isChecked() - Determines whether the chechbox is checked.
2. setChecked() - Sets or changes the state of the checkbox.
3. toggle() - Toggles state of the checkbox state from checked to unchecked or vice versa.
To add an EventListener, you can implement the OnCheckedChangeListener interface that invokes
the callback method onCheckedChanged() when the state of the checkbox changes.
In addition, you can also use the traditional implementation the onClickListener interface, that
invokes the onClick() method when any of the CheckBox controls are clicked.
Example:
<Checkbox android:id=”@+id/purchase”
android:layout_height=”wrap_content”
android:layout_width=”match_parent”
android:text=”purchase”/>
To learn concept of CheckBox. Let’s create an Android application based on these controls. Each
representing food item along with its price. When food items are selected, total price is displayed.
The application shows us how checkbox controls are displayed, how event Listener is attached to
them, and whether the checkbox is in a checked or unchecked state.
Launch Eclipse, create a new Android project called CheckBoxApp, and add three checkbox
controls to the Activity Layout file activity_check_box_app.xml, as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Items you Want"/>
<CheckBox
android:id="@+id/checkbox_pizza"
android:layout_height="wrap_content"
android:text="pizza $15"
android:layout_width="match_parent"/>
<CheckBox
android:id="@+id/checkbox_hotdog"
android:layout_height="wrap_content"
android:text="Hot Dog $5"
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 28
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:layout_width="match_parent"/>
<CheckBox
android:id="@+id/checkbox_burger"
android:layout_height="wrap_content"
android:text="Burger $10"
android:layout_width="match_parent"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bill_btn"
android:text="Calculate Bill"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/amount"/>
</LinearLayout>
You can see that two TextViews, three CheckBoxes and a Button control. The first TextView is
for displaying a message, Select Items you want, asking the user to select the food items using the
CheckBoxControls.
The three CheckBoxes are assigned unique ID’s — checkbox_pizza, checkbox_hotdog and
checkbox_burger — and they represent the food items, Pizza, HotDog and Burger respectively.
The caption and ID assigned to the button control are bill_btn and Calculate Bill respectively.
The second Text View is assigned the ID amount and is meant for displaying the totak price of the
food items selected by the user.
To add an action to the application, that is, to check the status of each of the checkbox controls and
to print the sum of the food items selected, You need to write some Java code in the activity file
shown below
package com.androidunleashed.checkboxapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.CheckBox;
import android.view.View;
import android.view.View.OnClickListener;
public class CheckBoxAppActivity extends Activity implements OnClickListener{
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 29
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
CheckBox c1,c2,c3;
TextView resp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_box_app);
Button b=(Button)this.findViewById(R.id.bill_btn);
resp=(TextView)this.findViewById(R.id.amount);
c1=(CheckBox)this.findViewById(R.id.checkbox_pizza);
c2=(CheckBox)this.findViewById(R.id.checkbox_hotdog);
c3=(CheckBox)this.findViewById(R.id.checkbox_burger);
b.setOnClickListener(this);
}
public void onClick(View v){
int amt=0;
if(c1.isChecked()){
amt=amt+15;
}
if(c2.isChecked()){
amt=amt+5;
}
if(c3.isChecked()){
amt=amt+10;
}
resp.setText("Bill is"+Integer.toString(amt));
}
}
The Button control with the ID bill_btn is accessed from the layout file and is mapped to the
Button object b. The TextView control with the ID amount is accessed from the layout file is
mapped to the TextView object resp.
Three CheckBoxes with the IDs checkbox_pizza, checkbox_hotdog, and checkbox_burger are
accessed from the layout file and mapped to the CheckBox objects c1,c2 and c3 respectively.
An event handler, setOnClickListener is attached to the button. Hence, whenever the button is
clicked, the OnClick() method is called. In the OnClick() method, an integer variable amt is
initialized to 0.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 30
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
The state of each check box is checked through the isChecked() method. The isChecked() method
returns the Boolean value true if the check box is checked; otherwise, it returns false. The three
check boxes represent the food items Pizza, HotDog and Burger, respectively.
if any of them is selected, the amount associated with that food item is added to the amt variable.
The total in the amt variable is displayed on the screen by assigning it to the TextView object resp.
When application is run, you get below Screens.
Choosing Mutually Exclusive Items Using RadioButtons
RadioButton controls are two-state widgets that can be in either a checked or unchecked state. The
difference between check boxes and radio buttons is that you can select more that one check box in
a set, whereas radiobuttons are mutually exclusive-only one radio button can be selected in a
group.
To make them mutually exclusive, RadioButton controls are grouped together into the RadioGroup
element so that no more than one can be selected at a time.
To create a group of radio buttons, first create a RadioGroup and then populate the group with few
RadioButtoncontrols, as shown in the following example:
<RadioGroup
android:id=”@+id/group_hotel”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:orientation=”vertical”>
<RadioButtonandroid:id=”@+id/radio_fivestar”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Five Star”/>
<RadioButtonandroid:id=”@+id/radio_threestar”
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 31
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Three Star”/>
</RadioGroup>
In the preceding code block, RadioGroup with the group_hotel ID is defined, which contains two
RadioButton controls with the IDs radio_fivestar and radio_threestar, respectively. Because only a
single radio button in a group can be in a checked state.
In Java, the following methods can be applied to RadioButtons:
1. isChecked() - Detects whether the RadioButton contrl is selected.
2. toggle() - Toggles the state of the RadioButton from selected to unselected and vice versa.
3. check() - Checks a specific RadioButton whose ID is supplied in the method.
4. getCheckedRadioButtonId() - Gets the ID of the currently selected RadioButton control. It
returns –1 if no RadioButton control is checked.
Let’s create an application using the concept of radio buttons. In this application, you define two
RadioButton controls in a RadioGroup. Each RadioButton represents a hotel type, and whenever a
RadioButton is selected, the hotel type represented by it will be displayed through a TextView
control.
Launch Eclipse,create a new Android project called RadioButtonApp, and add two RadioButton
controls to the Activity layout file activty_radio_button_app.xml, as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the type of hotel"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radio_fivestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Five Star"/>
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 32
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<RadioButton
android:id="@+id/radio_threestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three Star"/>
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hoteltype"/>
</LinearLayout>
you can see that two RadioButton controls with thradio_fivestar and radio_threestar IDs are
grouped inside a RadioGroup. This means that the two radio buttons have become mutually
exclusive.
To add an event listener action to the two RadioButton controls, you need to write some Java code
in the Activity file( RadioButtonAppActivty.java) shown below.
packagecom.androidunleashed.radiobutttonapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.RadioButton;
import android.view.View;
import android.view.View.OnClickListener;
public class RadioButtonAppActivty extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_radio_button_app);
RadioButton radioFivestar=(RadioButton)findViewById(R.id.radio_fivestar);
RadioButton radioThreestar=(RadioButton)findViewById(R.id.radio_threestar);
radioFivestar.setOnClickListener(radioListener);
radioThreestar.setOnClickListener(radioListener);
}
private OnClickListener radioListener=new OnClickListener(){
public void onClick(View v){
TextView selectedHotel=(TextView)findViewById(R.id.hoteltype);
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 33
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
RadioButton rb=(RadioButton) v;
selectedHotel.setText("The hotel type selected is:" + rb.getText());
}
};
}
The two RadioButton controls are captured from the layout and mapped to the RadioButton
objects radioFivestar and radioThreestar.
The View.OnClickListener interface is implemented to listen to the click events on the
RadioButton controls. The onClick() callback method is implemented. This is the method that is
executed when any of the RadioButton controls are selected.
In the onClick() callback method, the TextView control from the layout is captured and mapped to
the TextView object selctedHotel.
The text content of the RadioButton control that is selected by the user is fetched through the
getText() method and is displayed through the Textview object selected-Hotel.
On execution of the application, you see two RadioButton controls on the startup screen, as shown
below. When the user selects the five star RadioButton, the TextView displays the message “The
hotel type selected is: Five Star.”
When the user selects the threestar RadioButton, the Textview displays the message “The hotel
type selected is: Three Star”.
Similarly, the other RadioGroup that represents room types will have three RadioButton controls
to show three options: Ordinary Room, Luxury Room, and Grand Suite.
Add radiogroup control to preceding application. The layout file with two RadioGroup controls
appears as shown below.
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 34
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the type of hotel"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radio_fivestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Five Star"/>
<RadioButton
android:id="@+id/radio_threestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three Star"/>
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hoteltype"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the type of room"/>
<RadioGroup
android:id="@+id/group_room"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 35
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:id="@+id/radio_suite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Grand Suite"/>
<RadioButton
android:id="@+id/radio_luxury"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Luxury Room"/>
<RadioButton
android:id="@+id/radio_ordinary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ordinary Room"/>
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/roomtype" />
</LinearLayout>
To make two independent sets of radio buttons, one to represent hotel types and another to
represent room types, you create two RadioGroup controls with the group_hotel and group_room
IDs.
First RadioGroup, group_hotel, contains two RadioButton controls with the radio_fivestar and
radio_threestar IDs to represent five star and three star hotels.
Similarly, the next RadioGroup, group_room, contains three RadioButton controls with the
radio_suite, radio_luxury , and radio_ordinary IDs to represent the suite, luxury, and ordinary
room types.
The two TextView controls are used to display the messages select the type of hotel and select the
type of room, asking the user to select the type of hotel and room.
The third TextView with the hoteltype ID is used to display the options selected by the user. To
make the two RadioGroups functional and to display the hotel and room type selected by the user,
write the code shown below in the Java activity file RadioButtonAppActivity.java.
Package com.androidunleashed.radiobuttonapp;
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 36
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.RadioButton;
import android.view.View;
import android.view.View.OnClickListener;
public class RadioButtonAppActivity extends Activity{
String str1=" ";
String str2=" ";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_button_app);
RadioButton radioFivestar = (RadioButton) findViewById(R.id.radio_fivestar);
RadioButton radioThreestar=(RadioButton) findViewById(R.id.radio_threestar);
RadioButton radioSuite = (RadioButton) findViewById(R.id.radio_suite);
RadioButton radioLuxury = (RadioButton) findViewById(R.id.radio_luxury);
RadioButton radioOrdinary = (RadioButton) findViewById(R.id.radio_ordinary);
radioFivestar.setOnClickListener(radioListener1);
radioThreestar.setOnClickListener(radioListener1);
radioSuite.setOnClickListener(radioListener2);
radioLuxury.setOnClickListener(radioListener2);
radioOrdinary.setOnClickListener(radioListener2);
}
private OnClickListener radioListener1 = new OnClickListener(){
public void onClick(View v) {
TextView selectedOptions = (TextView) findViewById(R.id.hoteltype);
RadioButton rb = (RadioButton) v;
str1 = "The hotel type selected is: " + rb.getText();
selectedOptions.setText(str1 + "\n" + str2);
}
};
private OnClickListener radioListener2 = new OnClickListener(){
public void onClick(View v){
TextView selectedOptions = (TextView) findViewById(R.id.hoteltype);
RadioButton rb = (RadioButton) v;
str2="Room type selected is: "+rb.getText();
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 37
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
selectedOptions.setText(str1+"\n"+str2);
}
};
}
The RadioButton controls with IDs radio_fivestar, radio_threestar,radio_suite, radio_luxury and
radio_ordinary are captured from the layout file and mapped to the RadioButton objects
radioFivestar, radioThreestar, radioSuite, radioLuxury, and, radioOrdinary respectively.
Two event listener interfaces are created, radioListener1 and radioListener2. One checks for event
occurrences in the RadioButton contols in group_hotel, and the other checks for the occurrence of
events in the RadioButton controls in group_room. Both the interfaces have the callback method
onClick () implemented in them.
When any of the RadioButton controls in the first RadioGroup, group_hotel, is selected, the
callback method onClick() of radioListener1 is executed and text is assigned to the string str1 to
represent the RadioButton selected in that radio group.
When any RadioButton control from the second RadioGroup, group_room is selected, the callback
method onClick() of radioListener2 is executed. This assigns text to the string str2 to represent the
RadioButton selected in that radio group.
The TextView with the hotel_type ID is captured from the layout file and is mapped to the
TextView object selected Options. The text messages in both the str1 and str2 Strings are assigned
to the TextView control selectedOptions for display.
On running the application, you see two sets of RadioButton controls in their respective
RadioGroups as shown below
VISVODAYA INSTITUTE OF SCIENCE AND TECHNOLOGY, KAVALI 38
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
UNIT-III
CHAPTER-I
LAYING OUT CONTROLS IN CONTAINERS
Introduction to Layouts
Layouts are basically containers for other items known as views, which are displayed on
the screen. Layouts help manage and arrange views as well. Layouts are defined in the form of XML
files that cannot be changed by our code during runtime.
Layout Manager Description
LinearLayout Organizes its children either horizontally or vertically
RelativeLayout Organizes its children relative to one another or to the parent
AbsoluteLayout Each child control is given a specific location within the bounds of the
container
FrameLayout Displays a single view; that is, the next view replaces the previous view and
hence is used to dynamically change the children in the layout
TableLayout Organizes its children in tabular form
GridLayout Organizes its children in grid format
LinearLayout
The LinearLayout is the most basic layout, and it arranges its elements sequentially, either
horizontally or vertically. To arrange controls within a linear layout, the following attributes are used
android:orientation—Used for arranging the controls in the container in horizontal or vertical order
android: layout _width—Used for defining the width of a control
android:layout_height—Used for defining the height of a control
android:padding—Used for increasing the whitespace between the boundaries of the control and
its actual content.
android: Layout_weight—Used for shrinking or expanding the size of the control to consume the
extra space relative to the other controls in the container
android:gravity—Used for aligning content within a control
android:Layout_gravity—Used for aligning the control within the container
Applying the orientation Attribute
This attribute arranges its children in horizontal or vertical order. The valid values are horizontal
and vertical.
The orientation can be modified at runtime through the setOrientation() method. That is, by
supplying the values horizontal or vertical to the setOrientation() method.
VISVODAYA ENGINEERING COLLEGE, KAVALI 1
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Applying the height and width Attributes
The default height and width of the controls are decided on the basis of the text or content
displayed through it.
The values for the height and width attributes can specify in the following three ways:
By supplying specific dimension values for the control in terms of px (pixels), dip/ dp (device
independent pixels), sp (scaled pixels), pts (points), in (inches), and mm (millimeters). For
example, the android:layout_width="20px" attribute sets the width of the control to 20 pixels.
By providing the value as wrap_content. When assigned to the controls height or width, this
attribute resizes the control to fit its container.
By providing the value as match_parent. When assigned to the controls height or width, this
attribute resizes the control to fill its parent.
Applying the padding Attribute
The padding attribute is used to increase the whitespace between the boundaries of the control and
its actual content. The android:paddingLeft, android:paddingRight, android:paddingTop, and
android:paddingBottom attributes are used to specify the spaces individually.
android:padding=“5dip”, it sets the spacing on all four sides of the container.
android:paddingLeft="5dip", it sets the spacing on left side of the container.
To set the padding at runtime, we can call the setPadding() method.
Create a new android project called LinearlayoutApp. The default content of layout file
activity_linear_layout_app.xml is
<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/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".LinearLayoutAppActivity"/>
</LinearLayout>
Let's apply the LinearLayout and add three Button controls to the layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/Apple"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Apple" />
VISVODAYA ENGINEERING COLLEGE, KAVALI 2
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<Button
android:id="@+id/Mango"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Mango" />
<Button
android:id="@+id/Banana"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Banana" />
</LinearLayout>
The orientation of LinearLayout is set to vertical, so that we can arrange the controls one below the
other. We see the output as
Fig: Three Button controls arranged vertically in LinearLayout
To see the controls horizontally, set the orientation to horizontal. The layout_width of three
controls is set to wrap_content, otherwise we will be able to see only the first control. Modify the content
of layout file activity_linear_layout_app.xml to
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/Apple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Apple" />
<Button
android:id="@+id/Mango"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mango" />
<Button
android:id="@+id/Banana"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Banana" />
</LinearLayout>
VISVODAYA ENGINEERING COLLEGE, KAVALI 3
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
The controls are arranged horizontally as,
Fig: Three Button controls arranged horizontally in LinearLayout
Applying the weight Attribute
The weight attribute affects the size of the control. That is, we use weight to assign the capability
expand or shrink and consume extra space relative to the other controls in the container.
The values of the weight attribute range from 0.0 to 1.0, where 1.0 is the highest value.
The activity_linear_layout_app.xml File on Applying the weight Attribute to the Button Controls
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="wrap_content"
android:layout_height="wrap_content“
android:layout_weight=“0.0" />
<Button
android:id="@+id/Mango"
android:text="Mango
android:layout_width="wrap_content"
android:layout_height=wrap_content"
android:layout_weight="1.0" />
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="wrap_content"
android:layout_height=wrap_content"
android:layout_weight="0.0" />
</LinearLayout>
VISVODAYA ENGINEERING COLLEGE, KAVALI 4
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Fig: (left) The weight attribute of the Mango Button control set to 1.0, (middle) the weight attribute of the
Banana Button control set to 1.0, and (right) all three Button controls set to the same weight attribute
Similarly we set the weight of Apple, Mango, and Banana to 0.0, 1.0 and 0.5, respectively then
check the output.
Fig: The weight attribute of the Apple, Mango, and Banana Button controls set to 0.0, 1.0, and 0.5
Applying the Gravity Attribute
The Gravity attribute is for aligning the content within a control. For example, to align the text of a
control to the center, we set the value of its android:gravity attribute to center.
The valid options for android:gravity include left, center, right, top, bottom, center_horizontal,
center_vertical, fill_horizontal, and fill_vertical.
The task performed by few of the said options is as follows:
center _vertical—Places the object in the vertical center of its container, without changing
its size.
fill_vertical—Grows the vertical size of the object, if needed, so it completely fills its
container
center_horizontal—Places the object in the horizontal center of its container, without
changing its size.
fill_horizontal—Grows the horizontal size of the object, if needed, so it completely fills its
container.
center—Places the object in the center of its container in both the vertical and horizontal
axis, without changing its size.
We can also combine two or more values of any attribute using the | operator.
android:gravity="center_horizontal|center_vertical”
The following figure shows the android:gravity attribute set lo left and right for the button controls
Mango and Banana.
Fig: The text in the Mango and Banana Button controls aligned to the left and right, respectively, through the
android:gravity attribute
VISVODAYA ENGINEERING COLLEGE, KAVALI 5
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Using the android: layout_gravity Attribute
Where android:gravity is a Setting used by the View, the android: layout_gravity is used by the
container. That is, this attribute is used to align the control within the container.
First arrange the controls appear in vertical order, modify the activity_linear_layout_app.xml as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/Apple"
android:layout_width=" wrap_content"
android:layout_height="wrap_content"
android:text="Apple" />
<Button
android:id="@+id/Mango"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mango" />
<Button
android:id="@+id/Banana"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Banana" />
</LinearLayout>
To align the Button controls Mango and Banana to the center and to the right of the LinearLayout
container, add the following statements to the respective tags in the xml layout file:
android:layout_gravity="center“ and android:layout_gravity="right"(middle)
Fig: (left) The three Button controls vertically aligned with the width attribute set to wrap_content, (middle)
the Mango and Banana Button controls aligned to the center and right of container, and (right) the width of
the three Button controls expanded to take up all the available space.
If we now set the values of three controls to match parent ,the button controls will expand
to take up the available space of the container.(right in above fig)
Now we can apply the android gravity attribute to align the text within the controls. Add
the following three attributes to align the content to the left, center and right within the control.(left)
android:gravity="left" android:gravity="center" and android:gravity="right“
For example, assigning the android: layout_ weight=“1.0" to all three controls results in equal
division of empty space among them.(middle)
VISVODAYA ENGINEERING COLLEGE, KAVALI 6
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Fig: (left) The three Button controls with their text aligned to the left, center, and right, (middle) the vertical
available space of the container apportioned equally among the three Button controls, and (right) the text of
the three Button controls vertically aligned to the center
In the middle image, the text in apple and banana controls is not vertical center. So, modify
their android:gravity value as,
android:gravity="center_vertical" for the Apple control
android:gravity="center_vertical|right" for the Banana control(right)
RelativeLayout
In RelativeLayout, each child element is laid out in relation to other child elements; that is, the
location of a child element is specified in terms of the desired distance from the existing children. Create
a new android project called RelativeLayoutApp. Modify its layout file activity_relative_layout_app.xml
to appear as
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:layout_marginLeft="20dip"/>
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="28dip"
android:layout_toRightOf="@+id/Apple"
android:layout_marginLeft="15dip"
android:layout_marginRight="10dip"
android:layout_alignParentTop="true"/>
<Button
VISVODAYA ENGINEERING COLLEGE, KAVALI 7
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="200dip"
android:layout_height="50dip"
android:layout_marginTop="15dip"
android:layout_below="@id/Apple"
android:layout_alignParentLeft="true"/>
<Button
android:id="@+id/Grapes"
android:text="Grapes"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:minWidth="100dp"
android:layout_alignParentRight="true"
android:layout_below="@id/Banana"
android:gravity="center_horizontal"/>
<Button
android:id="@+id/Kiwi"
android:text="Kiwi"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_below="@id/Banana"
android:paddingTop="15dip"
android:paddingLeft="25dip"
android:paddingRight="25dip"/>
</RelativeLayout>
The different attributes used to set the positions of the layout controls.
Layout Control Attributes
The attributes used to set the location of the control relative to a container are
android: layout alignParentTop—The top of the control is set to align with the top of the container.
android: iayout_alignParentBottom—The bottom of the control is set to align with the bottom of
the container.
android: layout_alignParentLeft—The left Side of the control is Set to align with the left side of
the container.
android:layout_alignParentRight—The right side of the control is set to align with the right side of
the container.
android :layout_centerHorizontal—The control is placed horizontally at the center of the container.
android:layout centervertioal—The control is placed vertically at the center of the container.
android: layout_centerinParent—The control is placed horizontally and vertically at the center of
the container.
The attributes to control the position of a control in relation to other controls are
android :layout_above—The control is placed above the referenced control.
android :layout_beiow—The control is placed below the referenced control.
android: layout_toLeftof—The control is placed to the left of the referenced control.
android :layout_toRightof—The control is placed to the right of the referenced control.
VISVODAYA ENGINEERING COLLEGE, KAVALI 8
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
The attributes that control the alignment of a control in relation to other controls are
android: layout_alignTop— The top of the control is set to align with the top of the referenced
control.
android: layout_alignBottom—The bottom of the control is set to align with the bottom of the
referenced control.
android: layout_alignLeft—The left side of the control is set to align with the left side of the
referenced control.
android:layout_alignRight—The right side of the control is set to align with the right side of the
referenced control.
android: layout_alignBaseline—The baseline of the two controls will be aligned.
For spacing, Android defines two attributes android:layout_margin and
android:padding.The android:layout_margin attribute defines spacing for the container, while
android:padding defines the spacing for the view. Let's begin with padding.
android:padding—Defines the spacing of the content on all four sides of the control.
To define padding for each side individually, use
android:paddingTop—Defines the spacing between the content and the top of the control.
android:paddingBottom—Defines the spacing between the content and the bottom of the control.
android:paddingLeft—Defines the spacing between the content and the left side of the control.
android:paddingRight—Defines the spacing between the content and the right side of the control.
Here are the attributes that define the spacing between the control and the container:
android:layout_margin—Defines the spacing of the control in relation to the controls or the
container on all four sides. To define spacing for each side individually, we use the
android:layout_marginLeft, android:layout_marginRight, android:layout_marginTop, and
android:layout_raarginBottom options.
android:layout_marginTop—Defines the spacing between the top of the control and the related
control or container.
android:layout_marginBottom—Defines the spacing between the bottom of the control and the
related control or container.
android:layout_marginRight—Defines the spacing between the right side of the control and the
related control or container.
android:layout_marginLeft—Defines the spacing between the left side of the control and the
related control or container.
We don’t need to make any changes to the RelativeLayoutAppActivity.java file. Its original
content is
VISVODAYA ENGINEERING COLLEGE, KAVALI 9
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
package com.androidunleashed.relativelayoutapp;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extendsActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_relative_layout_app);
}
}
When the application is run, we see the output as
Fig: The five Button controls' layout relative to each other
The application we are going to create is simple login form application that asks the user to enter a
user id and password. The TextView, EditText and Button controls in the application are laid out in a
RelativeLayout container. If either the user ID or Password is left blank, the message The user ID or
password is left blank. Please Try Again is displayed. If the correct User ID and Password, in this case,
guest, are entered, then a welcome message is displayed. Otherwise, the message The User ID or
password is incorrect. Please Try Again is displayed.
Arrange four Textview controls, two EditText controls, and a Button control in RelativeLayout, as
shown in the layout file activity_login_form.xml
<RelativeLayout 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/sign_msg"
android:text="Sign In"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:typeface="serif"
VISVODAYA ENGINEERING COLLEGE, KAVALI 10
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:textSize="25dip"
android:textStyle="bold"
android:padding="10dip"
android:layout_centerHorizontal="true"/>
<TextView
android:id="@+id/user_msg"
android:text="User ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dip"
android:layout_below="@id/sign_msg"/>
<EditText
android:id="@+id/user_ID"
android:layout_width="250dip"
android:layout_height="wrap_content"
android:layout_below="@id/sign_msg"
android:layout_toRightOf="@+id/user_msg"
android:maxLines="1"/>
<TextView
android:id="@+id/psw_msg"
android:text="Password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/user_msg"
android:layout_margin="10dip"
android:paddingTop="10dip”/>
<EditText
android:id="@+id/psw"
android:layout_width="250dip"
android:layout_height="wrap_content"
android:maxLines="1"
android:layout_below="@id/user_ID"
android:layout_toRightOf="@id/psw_msg"
android:inputType="textPassword” />
<Button
android:id="@+id/login_button"
android:text="Sign In"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dip"
android:layout_below="@+id/psw_msg"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/resp"
android:layout_below="@id/login_button"/>
</RelativeLayout>
To authenticate the user, we need to access the User ID and Password that is entered and match
these values against the valid user ID and Password. In addition, we want to validate the EditText
controls to confirm that none of them is blank. We also want to welcome the user if he or she is
authorized. To do all this, we write the code in the activity file LoginFormActivity.java as
Package com.androidunleashed.loginform;
VISVODAYA ENGINEERING COLLEGE, KAVALI 11
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
import android.widget.Button;
public class LoginFormActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)this.findViewById(R.id.login_button);
b.setOnClickListener(this);
}
public void onClick(View v)
{
EditText uid= (EditText)findViewById(R.id.user_ID);
EditText psw= (EditText)findViewById(R.id.psw);
TextView resp= (TextView)this.findViewById(R.id.resp);
String usr=uid.getText().toString();
String pswd = psw.getText().toString();
if (usr.trim().length()==0 || pswd.trim().length()==0) {
String str = "The User ID or Password is left blank \nPlease Try Again.";
resp.setText(str);
}
else
{
if(usr.equals("guest")&& pswd.equals("guest"))
resp.setText("Welcome "+usr+" ! ");
else
resp.setText("The User ID or Password is Incorrect\nPlease Try Again.");
}
}
}
The Button control is accessed from the layout file and is mapped to the Button object b. This
activity implements the OnclickListener interface. Hence, the class implements the callback method
onClick( ), which is invoked when a click event occurs on the Button control. The output is as follows
Fig: (left) The Login Form displays an error if fields are left blank, (middle) the Password Incorrect message
displays if the user ID or password is incorrect, and (right) the Welcome message displays when the correct
user ID and password are entered.
VISVODAYA ENGINEERING COLLEGE, KAVALI 12
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
AbsoluteLayout
Each child in an AbsoluteLayout is given a specific location within the bounds of the container.
Such fixed locations make AbsoluteLayout incompatible with devices of different screen size and
resolution. The controls in AbsoluteLayout are laid out by specifying their exact X and Y positions. The
coordinate 0,0 is the origin and is located at the top-left corner of the screen.
The AbsoluteLayout class is not used often, as it is not compatible with Android phones of
different screen sizes and resolutions.
Create a new Android Project called AbsoiuteLayoutApp. Modify its layout file, activity_
absolute_layout_app.xml, as
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="90dip"
android:layout_y="2dip"
android:text="New Product Form"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product Code"
android:layout_x="5dip"
android:layout_y="40dip"/>
<EditText
android:id="@+id/p_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="110dip"
android:layout_y="30dip"
android:minWidth="100dip" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product Name"
android:layout_x="5dip"
android:layout_y="90dip"/>
<EditText
android:id="@+id/p_name"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:layout_x="110dip"
android:layout_y="80dip"
android:minWidth="200dip"
android:scrollHorizontally="true” />
VISVODAYA ENGINEERING COLLEGE, KAVALI 13
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product Price"
android:layout_x="5dip"
android:layout_y="140dip” />
<EditText
android:id="@+id/p_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="110dip"
android:layout_y="130dip"
android:minWidth="100dip" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Add New Product"
android:layout_x="80dip"
android:layout_y="190dip"/>
</AbsoluteLayout>
After specifying the locations of controls in the layout file activity_absoiute_iayout_ app.xml, we
can run the application. There is no need to make any changes in the file AbsoluteLayoutAppActivity.
java. When the application is run, we get the as
Fig: Different controls laid out in AbsoluteLayout
The AbsoluteLayout class is not used often, as it is not compatible with Android phones of
different screen sizes and resolutions.
VISVODAYA ENGINEERING COLLEGE, KAVALI 14
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Using ImageView
An imageview control is used to display images in Android applications. An image can be
displayed by assigning it to the imageview control and including the android: src attribute in the XML
definition of the control. Images can also be dynamically assigned to the ImageView control through
Java code.
A sample ImageView tag when used in the layout file is shown here:
<lmageView
android:id=“@+id/first_image"
android:src = "@drawable/bintupic"
android:layout_width="wrap_content"
android: layout_height= "wrap_content11
android: scaleType="fitXY"
android: adjustViewBounds=11 true"
android: maxHeight=“100dip"
android:maxWidth=“25Odip"
android:minHeight="100dip"
android: minWidth=“25Odip"
android:resizeMode="horizontal|vertical" />
android:src—Used to assign the image from drawable resources. You do not need to specify the
image file extension. JPG and GIF files are supported, but the preferred image format is PNG.
android:scaleType—Used to scale an image to fit its container. The valid values for this attribute
include fitXY, center, centerlnside, and fitCenter. The value fitXY independently scales the image
around the X and Y axes without maintaining the aspect ratio to match the size of container.
Android:adjustViewBounds—If set to true, the attribute adjusts the bounds of the imageview
control to maintain the aspect ratio of the image displayed through it.
android:resizeMode—The resizeMode attribute is used to make a control resizable so we can
resize it horizontally, vertically, or around both axes. The available values for the resizeMode
attribute include horizontal, vertical, and none.
FrameLayout
FrameLayout is used to display a single view. The view added to a FrameLayout is placed at the
top-left edge of the layout. Any other view added to the FrameLayout overlaps the previous view; that is,
each view stacks on top of the previous one.
To display images in Android applications, the image is first copied into the res/drawable folder
and from there, it is referred to in the layout and other XML files.
There are four types of drawable folders. We have to place images of different resolutions and
sizes in these folders. The graphics with the resolutions 320dpi, 240dpi, 160 dpi, and 120dpi (96 X 96
px, 72 x 72 px, 48 X 48 px, and 36 X 36 px), are stored in the res/drawable-xhdpi, res/drawable-hdpi,
VISVODAYA ENGINEERING COLLEGE, KAVALI 15
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
res/drawable-mdpi, and res/ drawable-ldpi folders, respectively. The application picks up the appropriate
graphic from the correct folder.
Create a new android project called FrameLayoutApp. To display two ImageViews and a
TextView in the application, let's write the code in the layout file activity_frame_layout_app.xml as
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/first_image"
android:src="@drawable/ex_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"/>
<ImageView
android:id="@+id/second_image"
android:src="@drawable/ex_2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click the image to switch"
android:layout_gravity="center_horizontal|bottom"
android:padding="5dip"
android:textColor="#ffffff"
android:textStyle="bold"
android:background="#333333"
android:layout_marginBottom="10dip" />
</FrameLayout>
When a user selects the current image on the screen, the image should switch to show the hidden
image. For this to occur, we need to write code in the activity file as
Package com.androidunleashed.framelayoutapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.view.View.OnClickListener;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_frame_layout_app);
final ImageView f_i=(ImageView)this.findViewById(R.id.first_image);
final ImageView s_i=(ImageView)this.findViewById(R.id.second_image);
f_i.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
VISVODAYA ENGINEERING COLLEGE, KAVALI 16
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
s_i.setVisibility(View.VISIBLE);
v.setVisibility(v.GONE);
}
});
s_i.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
f_i.setVisibility(View.VISIBLE);
v.setVisibility(v.GONE);
}
});
}
}
The application shows an image, and the other image is hidden behind it because in FrameLayout
one View overlaps the other. When the user clicks the image, the images are switched, as shown in the
following figure
Fig: (left) An image and a Textview laid out in FrameLayout, and (right) the images switch when clicked
TableLayout
The TableLayout is used for arranging the enclosed controls into rows and columns. Each new row
in the TableLayout is defined through a TabieRow object. A row can have zero or more controls, where
each control is called a ceil. The number of columns in a TableLayout is determined by the maximum
number of cells in any row. The width of a column is equal to the widest cell in that column.
Operations Applicable to TableLayout
We can perform several operations on TableLayout columns, including stretching, shrinking,
collapsing, and spanning columns.
Stretching Columns: The default width of a column is set equal to the width of the widest column,
but we can stretch the column(s) to take up available free space using the android: stretchcolumns
Examples:
1. android: stretchcolumns=“1"—The second column (because the column numbers are zero-
based) is stretched to take up any available space in the row.
VISVODAYA ENGINEERING COLLEGE, KAVALI 17
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
2. android:stretchcolumns= “0,1"—Both the first and second columns are stretched to take up
the available space in the row.
3. android:stretchcolumns="*"—All columns are stretched to take up the available space.
Shrinking Columns:We can shrink or reduce the width of the column(s) using the android:
shrinkcoiumns attribute in the TableLayout.
Examples:
1. android:shrinkcoiumns="0"—The first column's width shrinks or reduces by word-
wrapping its content.
2. android:shrinkcoiumns=“*"—The content of all columns is word-wrapped to shrink their
widths.
Collapsing Columns: We can make the column(s) collapse or become invisible through the
android: collapseColumns attribute in the TableLayout. For example
1. android:collapseColumns="0"—The first column appears collapsed; that is, it is part of the
table but is invisible. It can be made visible through coding by using the
setColumnCollapsed( ) method.
Spanning Columns: We can make a column span or take up the space of one or more columns by
using the android: layout_span attribute. The value assigned to this attribute must be >=1. For
example, the following value makes the control take or span up to two columns:
android:layout_span="2"
Let's try arranging controls in a TableLayout with an example. Create a new Android project called
TableLayoutApp. Make its layout file activity_table_layout_app.xml appear as
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width= "match_parent"
android:layout_height="match_parent"
android:stretchColumns="1">
<TableRow android:padding= "5dip">
<TextView
android:layout_height= "wrap_content"
android:text="New Product Form"
android:typeface="serif"
android:layout_span="2"
android:gravity= "center_horizontal"
android:textSize="20dip" />
</TableRow>
<TableRow>
<TextView
android:layout_height="wrap_content"
android:text="Product Code:"
android:layout_column="0"/>
<EditText android:id= "@+id/prod_code"
android:layout_height="wrap_content"
VISVODAYA ENGINEERING COLLEGE, KAVALI 18
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:layout_column="1"/>
</TableRow>
<TableRow>
<TextView android:layout_height= "wrap_content"
android:text="Product Name:"
android:layout_column="0"/>
<EditText android:id="@+id/prod_name"
android:layout_height = "wrap_content"
android:scrollHorizontally= "true" />
</TableRow>
<TableRow>
<TextView android:layout_height="wrap_content"
android:text="Product Price:" />
<EditText android:id="@+id/prod_price"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<Button android:id="@+id/add_button"
android:text="Add Product"
android:layout_height="wrap_content" />
<Button android:id="@+id/cancel_button"
android:text= "Cancel"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>
We cannot specify the layout width attribute for the controls enclosed within the TableLayout, as
their width will be always set to match_parent by default. We can specify the layout height attribute for
the enclosed controls. The layout_height attribute of the TableRow is always wrap_content.
If we don't specify a column number for any cell, it is considered to be the next available column.
When the application is run, the controls are laid out in rows and columns, as
VISVODAYA ENGINEERING COLLEGE, KAVALI 19
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Fig: Different controls arranged in TableLayout
GridLayout
GridLayout lays out views in a two-dimensional grid pattern, that is, in a series of rows and
columns. The intersection of row and column is known as a grid cell, and it is the place where child
views are placed. It is easier to use GridLayout when compared to TableLayout. Without specifying
intermediate views, we can flexibly place the views randomly in the grid by specifying their row and
column positions. More than one view can be placed in a grid cell.
Specifying Row and Column Position:
The two attributes that are used to specify the row and column position of the grid cell for inserting
views are android: layout_row and android: layout_column. Together, they specify the exact location of
the grid cell for placing the view. For example, the following statements place the view at the first row
and column position of the grid:
android: layout_row=”0” android: layout_column=”0“
Spanning Rows and Columns:
Views can span rows or columns if desired. The attributes are android: layout_rowSpan and
android: layout_columnSpan. For example, statement spans the view to two rows:
android:1ayout_rowSpan=”2”
Similarly, the following statement spans the view to three columns:
android: layout_columnSpan=”3”
Inserting Spaces in the GridLayout:
To insert spaces, the Space view is inserted as a child view. For example, the following statement
insert a space at the second row in the GridLayout.
VISVODAYA ENGINEERING COLLEGE, KAVALI 20
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<Space
android: layout_row=“1"
android: 1ayout_column="0"
android: layout_width="50dp"
android: layout_height="10dp" />
Similarly, the following statements insert a space at the third row in the GridLayout that spans
three columns:
<Space
android: layout_row=“3”
android:layout_column="0"
android:layout_columnSpan="3"
android:layout_gravity="fill" />
let's create a new Android project called GridLayoutLayoutApp. The application has controls
arranged in the same way as we saw in TableLayout. Make its layout file, activity_grid_layout_app.xml,
appear as
<GridLayout 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="horizontal"
android:rowCount="7"
android:columnCount="2" >
<TextView
android:layout_row="0"
android:layout_column="0"
android:text="New Product Form"
android:typeface="serif"
android:layout_columnSpan="2"
android:layout_gravity="center_horizontal"
android:textSize="20dip" />
<Space
android:layout_row="1"
android:layout_column="0"
android:layout_width="50dp"
android:layout_height="10dp" />
<TextView
android:layout_row="2"
android:layout_column="0"
android:text="Product Code:" />
<EditText
android:id="@+id/prod_code"
android:layout_width="100dip" />
<TextView
android:text="Product Name:" />
<EditText
android:layout_row="3"
android:layout_column= "1"
android:id="@+id/prod_name"
android:layout_width="200dip" />
<TextView
android:layout_row="4"
android:layout_column="0"
VISVODAYA ENGINEERING COLLEGE, KAVALI 21
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:text="Product Price:" />
<EditText
android:1ayout_row="4"
android:layout_column="1"
android:id="@+id/prod_price"
android:layout_width="100dip" />
<Space
android:layout_row="5"
android:layout_column="0"
android:layout_width="50dp"
android:layout_height = "20dp" />
<Button
android:layout_row="6"
android:layout_column="0"
android:id="@+id/add_button"
android:text="Add Product" />
<Button
android:id="@+id/cancel_button"
android:text="Cancel" />
</GridLayout>
In the preceding code, the GridLayout is defined as consisting of seven rows and two columns.
When the application is run, the controls are laid out in the grid pattern as
Fig: Controls organized in the GridLayout
Adapting to Screen Orientation
As with almost all smartphones, Android supports two screen orientations: portrait and landscape.
When the screen orientation of an Android device is changed, the current activity being displayed is
destroyed and re-created automatically to redraw its content in the new orientation.
Portrait mode is longer in height and smaller in width, whereas landscape mode is wider but
smaller in height. Being wider, landscape mode has more empty space on the right side of the screen. At
VISVODAYA ENGINEERING COLLEGE, KAVALI 22
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
the same time, some of the controls don't appear because of the smaller height. Thus, controls need to be
laid out differently in the two screen orientations because of the difference in the height and width of the
two orientations.
There are two ways to handle changes in screen orientation:
Anchoring controls—Set the controls to appear at the places relative to the four edges of the
screen. When the screen orientation changes, the controls do not disappear but are rearranged.
Defining layout for each mode—A new layout file is defined for each of the two screen
orientations. One has the controls arranged to suit the Portrait mode, and the other has the
controls arranged to suit the Landscape mode.
Anchoring controls:
For anchoring controls relative to the four edges of the screen, we use a RelativeLayout container.
Let's examine this method by creating an Android project called screenOrientationApp. Write the code
in the layout file activity_screen_orientation_app.xml as
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:layout_marginLeft="20dip"/>
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="28dip"
android:layout_toRightOf="@+id/Apple"
android:layout_marginLeft="15dip"
android:layout_marginRight="10dip"
android:layout_alignParentTop="true"/>
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="200dip"
android:layout_height="50dip"
android:layout_marginTop="15dip"
android:layout_below="@id/Apple"
android:layout_alignParentLeft="true"/>
<Button
android:id="@+id/Grapes"
android:text="Grapes"
android:layout_width="wrap_content"
android:layout_height="match_parent"
VISVODAYA ENGINEERING COLLEGE, KAVALI 23
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:minWidth="100dp"
android:layout_alignParentRight="true"
android:layout_below="@id/Banana"/>
<Button
android:id="@+id/Kiwi"
android:text="Kiwi"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_below="@id/Banana"
android:paddingTop="15dip"
android:paddingLeft="25dip"
android:paddingRight="25dip"/>
</RelativeLayout>
Five Button controls arranged in a RelativeLayout container. The controls are aligned relative to
the edges of the container .Let's keep the activity file screenOrientationAppActivity.java unchanged with
the default code, as
package com.androidunleashed.screenorientationapp;
import android.app.Activity;
import android.os.Bundle;
public class ScreenOrientationAppActivity extends Activity {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate (savedlnstanceState);
setContentView(R.layout.activity_screen_orientation_app);
}
}
When the application is run while in the default portrait mode, the controls appear as shown in Fig
(left). Because the five Button controls are placed in relation to the four edges of the container and in
relation to each other, none of the Button controls disappear if the screen is rotated to landscape mode, as
shown in Fig (right).
Fig: (left) Controls in portrait mode, and (right) the controls in landscape mode.
Defining Layout for Each Mode
VISVODAYA ENGINEERING COLLEGE, KAVALI 24
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
In this method, we define two layouts. One arranges the controls in the default portrait mode, and
the other arranges the controls in landscape mode. To understand this, let's write code for laying out the
controls for portrait mode in the default layout file activity_screen_orientation_app.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip"/>
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:padding="20dp"
android:layout_marginTop="20dip"/>
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="300dip"
android:layout_height="wrap_content"
android:padding="20dp"
android:layout_marginTop="20dip"/>
<Button
android:id="@+id/Grapes"
android:text="Grapes"
android:layout_width="300dip"
android:layout_height="wrap_content"
android:padding="20dp"
android:layout_marginTop="20dip"/>
<Button
android:id="@+id/Kiwi"
android:text="Kiwi"
android:layout_width="300dip"
android:layout_height="wrap_content"
android:padding="20dp"
android:layout_marginTop="20dip"/>
</LinearLayout>
we can see that five Button controls are vertically arranged in a LinearLayout container, one below
the other. This vertical arrangement makes a few of the Button controls disappear when the screen is in
landscape mode.
VISVODAYA ENGINEERING COLLEGE, KAVALI 25
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Fig: (left) Controls in portrait mode, and (right) some controls disappear in landscape mode.
To use the blank space on the right side of the screen in landscape mode, we need to define another
layout file, activity_screen_orientation_app.xml, created in the res/ layout-land folder. The layout-land
folder has to be created manually inside the res folder. Right-click on the res folder in the Package
Explorer window and select the New, Folder option. A dialog box opens, asking for the name for the
new folder. Assign the name layout-land to the new folder, and click the Finish button.
Copy the activity_screen_orientation_app .xml file from the res/layout folder and paste it into
res/layout-land folder. Modify the activity_screen_orientation_app.xml file in the res/layout-land folder
so as to arrange the controls in landscape mode.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height= "match_parent" >
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip" />
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip"
android:layout_toRightOf="@id/Apple" />
<Button
android:id="@+id/Banana"
android:text="Banana"
VISVODAYA ENGINEERING COLLEGE, KAVALI 26
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:layout_width="250dip"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip"
android:layout_below="@id/Apple" />
<Button
android:id="@+id/Grapes"
android:text="Grapes"
android:layout_width="250dip"
android:layout_height ="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip"
android:layout_below="@id/Apple"
android:layout_toRightOf="@id/Banana" />
<Button
android:id="@+id/Kiwi"
android:text="Kiwi"
android:layout_width="250dip"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip"
android:layout_below="@id/Banana" />
</RelativeLayout>
In this code block, we can see that, to fill up the blank space on the right side of the screen, the
Mango and Grapes button controls are set to appear to the right of the Apple and Banana button controls.
We can also detect the screen orientation via Java code. Let's modify the activity file
ScreenOrientationAppActivity.java to display a toast message when the screen switches between
landscape mode and portrait mode.
package com.androidunleashed.screenorientationapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_screen_orientation_app);
if(getResources().getDisplayMetrics().widthPixels>getResources().getDisplayMetrics().
heightPixels)
{
Toast.makeText(this,”screen switched to landscape mode”,Toast.LENGTH_SHORT).
Show();
}
else {
Toast.makeText(this,”screen switched to portrait mode”,Toast.LENGTH_SHORT).
Show();
}
}
}
VISVODAYA ENGINEERING COLLEGE, KAVALI 27
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Fig: (left) Controls in portrait mode, and (right) all controls are visible in landscape mode.
VISVODAYA ENGINEERING COLLEGE, KAVALI 28
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
UNIT-III
CHAPTER-II
UTILIZING RESOURCES AND MEDIA
Resources
Resources in Android refer to the external files that hold the information, such as strings, images,
layouts, and audio, to be supplied to an Android application. Because resources are external, we can
maintain and modify them whenever we want without disturbing the code. For example, the strings
resource keeps the strings used in an Android application.
Resources are broadly divided into three categories—values, drawable, and layout—and are stored
in the res folder of our project hierarchy.
The values resources in turn represent resources such as strings, colors, dimensions, styles, and
string or integer arrays.
All resource types have a respective subfolder in the res folder.
The ADT Wizard automatically creates a res folder that contains subfolders for the values,
drawable, and layout resources as
Fig:The res folder showing the nested drawable, layouts and values folders and their content
Types of Resources
A brief outline of the three folders is described here:
Drawable folder—Depending on the target platform chosen, our application can have either a
single directory, drawable, or four directories, drawable-ldpi, drawable-mdpi, drawable-hdpi, and
drawable-xhdpi, where we can store the images used in our application. If our application has a
single directory, drawable, then the images used, regardless of resolution, are stored in it.
VISVODAYA ENGINEERING COLLEGE, KAVALI 1
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
menu folder—This folder contains XML file(s) that represent application menus.
values folder—This folder by default contains a strings.xml file that we can use to define values
resources that include strings, colors, dimensions, styles, and string or integer arrays.
The following is a list of some XML files that we can create in the values folder:
o arrays.xml—For defining arrays resources.
o colors.xml—For defining color resources that define color values.
o dimens.xml—For defining dimension resources to standardize certain application
measurements.
o strings.xml—For defining string resources.
o styles.xml—For defining styles resources to format or change the appearance of our views
and application.
There are many Android devices with different Android versions, and managing themes across
them is a critical task. To manage themes for different Android versions, different values folders in
the /res folder containing individual themes are maintained.
values-v11—The folder contains the styles .xml file that declares the holographic theme, which is
used when the application runs on Android 3.0 (API Level 11) or higher.
values-v14—The folder contains the styles .xml file that declares the Device Default theme, which
is used when the application runs on Android 4.0 (API Level 14) or higher.
Table shows the list of supported subdirectories in the res folder.
Subdirectory Name Stores
anim Files that define animations.
color XML files that define a list of colors.
drawable-xhdpi Extra high resolution images. The xhdpi stands for extra high dots per inch.
drawable-hdpi High-resolution images. The hdpi stands for high dots per inch.
drawable -ldpi Low-resolution images. The ldpi stands for low dots per inch.
drawable-mdpi Medium-resolution images. The mdpi stands for medium dots per inch.
menu XML files that represent application menus.
raw Non-XML data such as audio files.
xml Additional XML files used in our application.
libs Reference libraries.
On compilation, an R class file is created that contains references to all the resources
created and hence enables us to reference them in the Java code. For each of the resource types, the R
class contains static subclasses for string, drawable, and layout resource types.
VISVODAYA ENGINEERING COLLEGE, KAVALI 2
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Creating Values Resources
The resources in the values directory include different types, such as strings, colors, dimensions,
and string or integer arrays. All the values are stored in XML files in the res/values folder. The filename
can be anything, but most commonly, the string resources file is named strings .xml. Remember, the
resource filenames should contain only lowercase letters, numbers, period (.), and underscore (_)
symbols.
To create Values resources, let's create an Android project called valuesResourcesApp. The strings
.xml file that is automatically created.Default Code in the strings.xml File is
<resources>
<string name="app_name”>ValuesResourcesApp</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string
name=“title_activity_values_resources_app">ValuesResourcesAppActivity</string>
</resources>
The two string resources with the name attributes hello and app_name are assigned to the Textview
(in main, xml) and label attribute of the Activity tag (in AndroidManifest .xml) to display the name of
the activity and the application name.Code Written in the strings.xml File
<resources>
<string name="app_name">ValuesResourcesApp</string>
<string name="menu_settings">Settings</string>
<string
name="title_activity_values_resources_app">ValuesResourcesAppActivity</string>
<string name="str_name">XYZ Restaurant</string>
<string name="str_address">11, Hill View Street, New York</string>
<string name="str_message" ><b>Welcome</b></string>
</resources>
The string resources file has a root element, <resources>, followed by one or more child
elements, <string>. Each <string> element represents one string resource. Besides the text for the string
resource, it contains a name property used to assign a unique resource ID to the string.
We can use the string resources of the preceding XML file in other resource files by using the
following syntax:
@string/resource_ID
For example, @string/str_address
All the string resources mentioned in the preceding string resource file will be compiled and placed
in the R. java file. In the Java code, we can access the resources from the r. java file, using the following
syntax:
R.string.resource_ID
There is no need to add any prefix while accessing any control from the layout. The resource ID is
enough. The syntax is
R.id.resource_ID
VISVODAYA ENGINEERING COLLEGE, KAVALI 3
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
We use the getString() method and pass the resource ID of the concerned string resource to access
it in Java code.
getString(R.string.str_address);
To access the string resources defined in the file strings.xml and to apply them to the Textview
controls, the layout file activity_values_resources_app.xml may be modified to appear as
<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/name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name" />
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Textview
android:id="@+id/message_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_message" />
</LinearLayout>
The code written in the Java file valuesResourcesAppActivity.java may appear as
package com.androidunleashed.valuesresourcesapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_values_resources_app);
String strAddress=getString(R.string.str_address);
TextView addressView=(TextView)findViewById(R.id.address_view);
addressView.setText(strAddress);
}
}
We get the output as
Fig: The three Textviews displaying the text assigned to them via String resource and Java code
VISVODAYA ENGINEERING COLLEGE, KAVALI 4
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Dimension Resources
Dimension resources are used for standardizing certain application measurements. These resources
can be used to specify the sizes for fonts, layouts, and widgets. Also, we can modify the size of any
control in the application without changing the code.
Code Written in the dimens.xml File
<resources>
<dimen name="small_size">15dp</dimen>
<dimen name="medium_size">15sp</dimen>
<dimen name="large_size">20pt</dimen>
</resources>
We can use any of the following units of measurement:
px—Pixels
in—Inches
mm—Millimeters
pt—Points
dp—Density-independent pixels based on a 160-dpi (pixel density per inch) screen
sp—Scale-independent pixels
In the strings.xmi file, we have defined three dimension resources: 15dp, 15sp, and 20pt,
represented by the three resource IDs small_size, medium_size, and large_size. To apply dimension
resources to the Textview controls, modify activity_values_resources_app.xml to appear as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation= "vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/name_view"
android:layout_width= "match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name"
android:textSize="@dimen/small_size" />
<TextView
android:id="@+id/address_view"
android:layout_width= "match_parent"
android:layout_height ="wrap_content" />
<TextView
android:id="@+id/message_view"
android:layout_width= "match_parent"
android:layout_height="wrap_content"
android:text = "@string/str_message"
android:textSize="@dimen/large_size" />
</LinearLayout>
To apply the dimension resource medium size to our Textview address_view, add these statements
to the Java file ValuesResourcesAppActivity. java:
float addressSize= this.getResources().getDimension(R.dimen.medium_size);
addressView.setTextSize(addressSize);
VISVODAYA ENGINEERING COLLEGE, KAVALI 5
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
We get the output as
Fig: Different dimensions applied to the three Textviews via dimension resources
Color Resources
To define a color resource, use the color element. The color value is specified in the form of
hexadecimal RGB values preceded by an optional Alpha channel. The Alpha channel represents the
transparency. We can specify the color either through single-character hex values or double-character
hex values formats, as shown here:
#RGB—For example, #F00 for a Red color.
#RRGGBB—For example, #FF0000 for a Red color
#ARGB—For example, #5F00 for a Red color with an Alpha of 5.
#AARRGGBB—For example, #50FF0000 for a Red color with an Alpha of 50.
To apply color resources to our application valuesResourcesApp, let's add an XML file called
colors.xml to the values folder.
<resources>
<color name="red_color">#F00</color>
<color name="green_color">#00FF00</color>
<color name="blue_alpha_color">#500000FF</color>
</resources>
To apply color resources via the layout file activity_values_resources_app .xml, let's modify it to
appear as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation= "vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/name_view"
android:layout_width= "match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name"
android:textSize="@dimen/small_size"
android:textColor="@color/red_color"/>
<TextView
android:id="@+id/address_view"
android:layout_width= "match_parent"
android:layout_height ="wrap_content" />
VISVODAYA ENGINEERING COLLEGE, KAVALI 6
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<TextView
android:id="@+id/message_view"
android:layout_width= "match_parent"
android:layout_height="wrap_content"
android:text = "@string/str_message"
android:textSize="@dimen/large_size"
android:textColor="@color/blue_alpha_color"/>
</LinearLayout>
To apply the color resource to the Textview address_view, we use Java code. Add the following
lines of code to the Java file ValuesResourcesAppActivity. Java.
int addressColor=this.getResources().getColor(R.color.green_color);
addressView.setTextColor(addressColor);
When the application is run, we see the three Textview controls appear as
Fig: The three Textviews displayed in different colors applied via the Color Resource.
Styles and Themes
A style is a collection of attributes such as color, font, margin, and padding that can apply
collectively to views, Activity, or an entire application. That is, instead of applying attributes
individually to the components of an application.
A style is created by using a style element with one or more item child elements. The style element
includes a name property to specify the resource ID.
An item element defines an attribute and its value shown in this syntax:
<resources>
<style name="resource_ID">
<item name="attribute_name">value </item>
</style>
</resources>
Styles support inheritance; that is, the attributes of any existing style can be accessed and included
in the current style by using the parent property. To apply styles to the individual views in the layout file,
open the styles .xml file that already exists in the values folder. In the styles.xml file, define the styles as
<resources>
<style name="AppTheme" parent="android:Theme.Light" />
<style name="style1">
<item name="android:textColor">#00FF00 </item>
<item name="android:typeface">serif</item>
<item name="android:textSize">30sp </item> </style>
VISVODAYA ENGINEERING COLLEGE, KAVALI 7
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<style name="style2" parent="style1" >
<item name="android:textColor">#0000FF</item>
<item name="android:typeface">sans</item>
<item name="android:background" >#FF0000</item>
<item name="android:padding">10dip</item> </style>
<style name="style3" parent="style2" >
<item name="android:textColor">#00FF00</item>
<item name="android:background">#00000000</item>
<item name="android:typeface">monospace</item>
<item name= "android:gravity">center</item>
</style>
</resources>
Let's apply the three styles to the three Textview controls. Modify the layout file as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation= "vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/name_view"
style="@style/style1"
android:layout_width= "match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name"/>
<TextView
android:id="@+id/address_view"
style="@style/style2"
android:layout_width= "match_parent"
android:layout_height ="wrap_content"
android:text="@string/str_address" />
<TextView
android:id="@+id/message_view"
style="@style/style3"
android:layout_width= "match_parent"
android:layout_height="wrap_content"
android:text = "@string/str_message" />
</LinearLayout>
We don't need any code in the Java activity file. So remove all the code that we have been adding
to it. When the application run, we see the output as
Fig: The three Textviews with different styles applied to them
VISVODAYA ENGINEERING COLLEGE, KAVALI 8
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Applying Themes
Apply the style element to an entire Activity or application by adding the android: theme
attribute to the Android manifest. For example, after add the android: theme attribute to the <activity>
element in the Android manifest, all the attributes of the style are applied to every view within the
Activity.
Let's apply style3, which defined in the styles.xml file, to the entire application by modifying the
android: theme attribute in AndroidManifest .xml file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidunleashed.valuesresourcesapp"
android:versionCode="1" android:versionName=“1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
andro id:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/style3” >
<activity
android:name=".ValuesResourcesAppActivity"
android:labels"@string/title_activity_values_resources_app" >
<intent-filter>
<action android:name= "android. intent .action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filters>
</activity>
</application>
</manifest>
To see the impact of applying the style to the entire application, we need to remove the styles in
the layout file that were applied to the individual Textview controls. So, modify
activity_values_resources_app.xml to appear as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation= "vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/name_view"
android:layout_width="match_parent"
android:layout_height= "wrap_content"
android:text="@string/str_name" />
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_address" />
<TextView
android:id="@+id/message_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_message" />
</LinearLayout>
VISVODAYA ENGINEERING COLLEGE, KAVALI 9
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
After the application is run, we find that the content of all three views appears in monospace font,
green foreground color, black background color, 30sp in size, and the text appears at the center of the
container.
Arrays
Arrays refer to a collection of values or elements.
Any element in an array can be referenced directly by specifying its index/subscription value.
Arrays can be in the form of strings or integers and are used for storing the data of their respective
data type.
Using String Arrays
The string array provides an array of strings.selection widgets such as ListView and spinner that
need to display a collection of selectable items to the user. To define a string array, we use the following
syntax:
<string-array name="array_name">
<item>text1</item>
<item>text2</item>
...
</string-array>
The name property acts as the resource ID and text1, text2, and so on represent the elements of the
string. The syntax for defining an integer array is shown here:
<integer-array name="array_name">
<item>number1</item>
<item>number2</item>
...
</integer-array>
Code in the strings.xml file on adding a String Array
<resources>
< string name ="app_name"> StringArrayApp</string >
<string name="menu_settings">Settings</string>
<string name="title_activity_string_array_app">StringArrayAppActivity</string>
<string-array name="fruits”>
<item>Apple</item>
<item>Mango</item>
<item>Orange</item>
<item>Grapes</item>
<item>Banana</item>
</string-array>
</resources>
Code in the Layout File activity_string_array_app.xml on Adding the TextView Control
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fruits_view"
VISVODAYA ENGINEERING COLLEGE, KAVALI 10
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Code Written in the Java Activity File StringArrayAppActivity.java
package com.androidunleashed.stringarrayapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Textview;
public class StringArrayAppActivity extends Activity {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_string_array_app);
Textview fruitsView = (Textview)findViewByld(R.id.fruits_view);
String [] fruitsArray = getResources().getStringArray(R.array.fruits);
String str = "";
for(int i = 0; i < fruitsArray.length; i++)
{
str += fruitsArray[i] + "\n";
}
fruitsView.setText(str);
}
}
The string elements collected in the str element are assigned to the Textview fruitsview for display.
After the application is run, all the string elements are displayed in the Textview, as
Fig: The content of the string array displayed through a Textview
Using Integer Arrays
Creating an integer array is similar to creating a string array. Code in the strings.xml file on adding
a integer Array.
<resources>
<string name="app_name">StringArrayApp</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_string_array_app">StringArrayAppActivity</string>
<integer-array name="OddNumbers">
<item>1</item>
<item>3</item>
<item>5</item>
<item>7</item>
<item>9</item>
</integer-array>
</resources>
VISVODAYA ENGINEERING COLLEGE, KAVALI 11
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Code Written in the Java Activity File StringArrayAppActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class StringArrayAppActivity extends Activity{
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_string_array_app);
TextView oddNumsView = (TextView)findViewById(R.id.oddnums_view);
int[] oddNumsArray = getResources().getIntArray(R.array.OddNumbers);
String str = "";
for(int i = 0; i < oddNumsArray.length; i++)
{
str += oddNumsArray[i] + "\n";
}
oddNumsView.setText(str);
}
}
After the application is run, all the values are displayed in the Textview, as
Fig: The content of a numeric array displayed through a Textview
Using Drawable Resources
Android supports three common image formats: PNG, JPG, and GIF.
The images for the Android application are stored in the directory res/drawable.
Depending on the target platform chosen while creating a new application, ADT either creates a
single directory, res/drawable, or several: drawable-ldpi, drawable- mdpi, drawable-hdpi, and
drawable-xhdpi.
Each directory is meant for storing images of different screen resolutions.
Remember, all image file names should be lowercase and contain only letters, numbers, and
underscores. After adding images to the res/drawable folders, the gen folder is regenerated where the r.
java file resides. The r. java file includes a reference to the newly added image and hence can be used in
the layout file or other Java code.
The syntax for referencing the image in the layout file is
@drawable/image_filename
In Java code, the image can be referenced using the following syntax:
R. drawable. image_filename
VISVODAYA ENGINEERING COLLEGE, KAVALI 12
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Remember, the image file name in the syntax shown refers to the base name of the file, that is, the
file name without the extension. To display the image, let's add an imageview control to the layout file.
Write the code in the layout file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image_toview"
android:src="@drawable/first_image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
We don't need to write any Java code for displaying the image. After the application is run, the
image is displayed, as
Fig: The image displayed through an imageview control using a drawable resource
We can specify the image for the image view control through Java code. To try this, let's remove
the reference to the image in the imageview control that made through the src attribute.
package com.androidunleashed.dispimageapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
public class DisplayImageAppActivity extends Activity {
@Override
public void onCreate(Bundle savedlnstanceState){
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_display_image_app);
ImageView image=(ImageView) findViewById(R.id.image_toview);
image.setImageResource(R.drawable.first_image) ;
}
}
VISVODAYA ENGINEERING COLLEGE, KAVALI 13
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Switching States with Toggle Buttons
The ToggleButton toggles between the two states, something like a radio button.
A ToggleButton can only be in one state out of two mutually exclusive states, for example, on and
off. To display a ToggleButton, use the <ToggleButton> tag in the layout file.
To set the text for the button, the two attributes android: textOn and android:textOff are used. The
default values for the two attributes are on and off, respectively.
<ToggleButton
android:layout_width= "wrap_content"
android:layout_height="wrap_content"
android:textOn="Play"
android:textOff="Stop" />
This code defines a toggle button that shows the text play in on state and stop in off state.
After we define the two controls, the code in the layout file activity_toggle_button_app. xml appears as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the Play button"
android:id="@+id/response"/>
<ToggleButton android:id="@+id/playstop_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Play"
android:textOff="Stop"/>
</LinearLayout>
To enable the ToggleButton to switch text via the Textview control when it is clicked, we need to
write some Java code in the ToggleButtonAppActivity. java file as
import android.app.Activity;
import android.os.Bundle ;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.view.View.OnClickListener;
import android.view.View;
public class ToggleButtonAppActivity extends Activity{
@Override
public void onCreate(Bundle savedlnstanceState){
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_toggle_button_app);
final TextView resp =(TextView)this.findViewById(R.id.response);
final ToggleButton
playStopButton=(ToggleButton)findViewById(R.id.playstop_btn);
playStopButton.setChecked(true);
playStopButton.setOnClickListener(new OnClickListener() {
VISVODAYA ENGINEERING COLLEGE, KAVALI 14
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
public void onClick(View v) {
if (playStopButton.isChecked() ) {
resp.setText("Stop button is toggled to Play button");
}
else {
resp.setText("Play button is toggled to Stop button");
}
}
});
}
}
When the ToggleButton is selected, its caption changes to stop, and the text in the Textview
changes to play button is toggled to stop button, as shown in Fig (middle). When the ToggleButton is
selected again, the caption in the ToggleButton changes back to Play, and the text in the Textview
control changes to stop button is toggled to Play button, as shown in Fig (right). That is, the caption in
the ToggleButton, as well as the text in the Textview controls, changes on every click of the
ToggleButton.
Fig: (Left) The ToggleButton and Textview on application startup, (middle) the text on ToggleButton and Textview changes
on selecting the ToggleButton, and (right) the original text on ToggleButton reappears on clicking the ToggleButton again.
We can also add a background image to the ToggleButton by adding the android:background
attribute to the <ToggleButton> tag in the layout file.
To align the text in center of TextView control:
android:gravity=“center”
To make the ToggleButton appear at the center of layout:
android:layout_gravity=“center”
The following statement sets the first_image.png image as the background image of the
ToggleButton.
android:background=”@drawable/first_image“
After we add the android: layout_gravity and android: background attributes, the ToggleButton
appears with a background image and at the center of the LinearLayout container, as shown in Fig (left).
Fig (middle and right) shows how the ToggleButton's text and Textview's text change with a click of the
ToggleButton.
VISVODAYA ENGINEERING COLLEGE, KAVALI 15
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Fig: (left) The ToggleButton with background image applied and a Textview on application startup, (middle) the text on the
ToggleButton and Textview changes on selecting the ToggleButton—the background image remains the same, and (right)
the original text on the ToggleButton reappears on clicking the ToggleButton again.
we notice that, although the ToggleButton's text changes on every click, its background image
remains the same. This is so because we defined the common background of the ToggleButton.To
display different background images for the on and off states of the ToggleButton, we need to add two
images to the application. Let's paste two images called, play.png and stop.png, into the res/drawable
folder. Add some Java code to our ToggleButtonAppActivity. java file as
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.view.View.OnClickListener;
import android.view.View;
public class ToggleButtonAppActivity extends Activity{
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_toggle_button_app);
final TextView resp=(TextView)this.findViewById(R.id.response);
final ToggleButton playstopbutton=(ToggleButton)findViewById(R.id.playstop_btn);
playstopbutton.setChecked(true);
playstopbutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (playstopbutton.isChecked() ) {
playstopbutton.setBackgroundDrawable(getResources().getDrawable(R.drawable.play));
resp.setText("Stop button is toggled to Play button");
}
else {
playstopbutton.setBackgroundDrawable(getResources().getDrawable(R.drawable.stop));
resp.setText("Play button is toggled to Stop button");
}
}
});
}
}
we don't want any text to appear on top of the images of the ToggleButton, let's remove the
text of the on and off states. Modify the android:textOn and android:textOff attributes in the
<ToggleButton> tag Of the layout file main.xml. We make the two attributes appear as
android:textOn="" android:textOff=""
VISVODAYA ENGINEERING COLLEGE, KAVALI 16
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
After the application is run, we find the output as
Fig:The ToggleButton with a background image (no text) and the Textview on application startup, (middle) the
background image of the ToggleButton and Textview changes on selecting the ToggleButton, and (right) the
original background image reappears on the ToggleButton on clicking the ToggleButton again.
Creating an Image Switcher Application
We just learned how the ToggleButton works, so let's use it to modify our earlier application,
DispimageApp, into an Image Switcher application.
On startup, this application initially displays an image through an imageview control with a
ToggleButton at the bottom of the screen.
When the ToggleButton is clicked, the image displayed in the imageview control changes.
After we click the ToggleButton again, the previous image is redisplayed in the imageview
control.
Because we want the application to switch images, we need to add one more image to the
application, called second_image.png to the res/drawable folder.
We want the application to show an image on startup (first_image.png) through the imageview
control, along with a ToggleButton at the bottom of the display. We need to modify our layout file as,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientat ion= "vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/image_toview"
android:src="@drawable/first_image"
android:layout_width="wrap_content"
android:layout_height ="wrap_content"
android:adjustViewBounds="true" />
<ToggleButton android:id="@+id/change_image"
android:layout_width="wrap_content"
android:layout_height= "wrap_content"
android:textOn=" Previous Image "
android:textOff="Next Image"
android:layout_gravity="center"
android:layout_marginTop=“ 10dip” />
</LinearLayout>
VISVODAYA ENGINEERING COLLEGE, KAVALI 17
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
To enable the ToggleButton to switch images, we need to write some Java code in the
DisplayImageAppActivity.java file as
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView ;
import android.widget.ToggleButton;
import android.view.View;
import android.view.View.OnClickListener;
public class DisplayImageAppActivity extends Activity {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_display_image_app);
final ImageView image = (ImageView) findViewById(R.id.image_toview);
final ToggleButton changeButton= (ToggleButton) findViewById(R.
id.change_image);
changeButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if (changeButton.isChecked()) {
image.setImageResource(R.drawable.second_image);
}
else {
image.setImageResource(R.drawable.first_image);
}
}
});
}
}
After the application is run, we find that the first image, first_image.png, is displayed through the
ImageView control along with the ToggleButton, and the text Next image is displayed at the bottom.
When the ToggleButton is clicked, the image displayed through the imageview control switches to
second_image.png, and the button text of the ToggleButton changes to Previous Image, as
Fig: (left) An image displayed through the imageview control with a ToggleButton below it, and (right) the
image in the imageview switches when the ToggleButton is selected.
VISVODAYA ENGINEERING COLLEGE, KAVALI 18
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Scrolling Through Scrollview
A scrollview is a special type of control that sets up a vertical scrollbar in a view container.
This control is used when we try to display views that are too long to be accommodated in a single
screen.
The scrollview can have only one child view, so usually a view container layout is used as a child,
which in turn contains other child controls that we want to scroll through.
All the child controls in the layout have one continuous scrollbar.
Create a new application called ScrollViewApp. In this application we place three images
one below the other. The three images cannot fit into a single screen, so we use scrollView control to
scroll them vertically.Copy the three images into drawable folder. Modify the layout file as,
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollwid"
android:layout_width= "match_parent"
android:layout_height = "match_parent"
android:fillViewport="true"
android:orientation="vertical" >
<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" >
<ImageView
android:id="@+id/image_toview"
android:src="@drawable/first_image"
android:layout_width="200dip"
android:layout_height="250dip"
android:layout_gravity="center" />
<ImageView
android:id= "@+id/image_toview2"
android:src="@drawable/second_image"
android:layout_width="200dip"
android:layout_height="250dip"
android:layout_gravity= "center"
android:layout_marginTop="10dip" />
<ImageView
android:id="@+id/image_toview3"
android:src="®drawable/third_image"
android:layout_width="200dip"
android:layout_height="250dip"
android:layout_gravity="center"
android:layout_marginTop="10dip" />
</LinearLayout>
</ScrollView>
Use Of the android: fillviewport Attribute: When set to true, the android: fillviewport attribute makes
the child controls of the scrollview expand to the size of the display. If the size of child controls is
already larger than the display, the attribute has no effect.
VISVODAYA ENGINEERING COLLEGE, KAVALI 19
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
We don't have to write any code in activity file scrollviewAppActivity.java. The default code is
package com.androidunleashed.scrollviewapp;
import android.app.Activity;
import android.os.Bundle;
public class ScrollviewAppActivity extends Activity {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_scroll_view_app);
}
}
We can see that in the main.xml file, the LinearLayout container holding the three imageview
controls is made child of a scrollview control. The vertical scroller therefore appears on the right side of
the images, as
Fig: (left) Two fixed images are displayed, and (right) scrolling images are displayed.
Playing Audio
Make a new Android project called playAudioApp. The audio that we want to play needs to be
added to this application.
Adding Audio to the Application
The audio file that we want to play must be located in the res/raw folder of our application. The
raw folder isn't created automatically, so we need to create it manually.Right-click the res folder in the
Package Explorer window and select New, Folder. In the dialog box that opens, enter the name of the
new folder as raw and click the Finish button.
In the raw folder, let's copy an audio file called tit.mp3. The Java class r. java file is automatically
regenerated after the audio file is added to the application allowing us to access it. The res folder looks
like,
VISVODAYA ENGINEERING COLLEGE, KAVALI 20
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
we want to display a Textview and a Button control. Textview displays instructions, and the
Button control initiates an action. To add the two controls, write the code in the layout file
activity_play_audio_app.xml as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Playing Audio" />
<Button android:id="@+id/playbtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Play" />
</LinearLayout>
To play the audio when the button is clicked, write the code in the activity file
PlayAudioAppActivity.java as
import android.app. Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.media.MediaPlayer;
public class PlayAudioAppActivity extends Activity {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_play_audio_app);
Button playButton = (Button) findViewByld(R.id.playbtn);
playButton.setOnClickListener(new Button.OnclickListener() {
public void onClick(View v) {
MediaPlayer mp =
MediaPlayer.create(PlayAudioAppActivity.this,R.raw.tit) ;
VISVODAYA ENGINEERING COLLEGE, KAVALI 21
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
mp.start();
}
});
}
}
When the Play button is clicked, the audio, tit.mp3, is played.
Fig: The Textview and a Play Button control on application startup
We can display an image on the Button control by adding the following attributes to the <Button>
element:
android:drawableTop—The image is displayed above the button text.
Example: android: drawableTop= “@drawable/ ic_launcher “
android:drawableBottom—The image is displayed below the button text
android:drawableLeft—The image is displayed to the left of the button text
android:drawableRight—The image is displayed to the right of the button text
PlayAudioApp works fine, but it doesn't have a stop or Pause button to stop and resume
playing the audio.we replace the Button Control with the ToggleButton Control. The layout file
activity_play_ audio_app. xml now appears as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width= "match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:id="@+id/response"/>
<ToggleButton android:id="@+id/playstop_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Stop"
android:textOff= "Play"
android:layout_gravity="center" />
</LinearLayout>
VISVODAYA ENGINEERING COLLEGE, KAVALI 22
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
To stop and resume the audio with a click of the ToggleButton, we write the Java code as shown in
the PlayAudioAppActivity. java file
import android.App.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.view.View;
import android.media.MediaPlayer;
public class PlayAudioApp extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_audio_app);
final TextView response = (TextView)this.findViewById(R.id.response);
response.setText("Select Play button to play audio");
final MediaPlayer mp = MediaPlayer.create(PlayAudioApp.this,R.raw.tit);
final ToggleButton playStopButton = (ToggleButton)
findViewById (R.id.playstop_btn) ;
playStopButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if (playStopButton.isChecked() ) {
response.setText("Select Stop button to stop audio");
mp.start();
}
else {
response.setText("Select Play button to play audio");
mp.pause();
}
}
});
}
}
If we select the ToggleButton, the audio begins playing, the text on the ToggleButton changes to
stop, and the text displayed through the Textview is changed to select stop button to stop audio, as
Fig: (left) Audio plays on selecting the ToggleButton, and (right) the text on the ToggleButton and TextView
changes on selecting the ToggleButton
To change the displays as Play and stop images in the ToggleButton instead of plain text. We need
to add two images, play .png and stop. png, to the res/drawable folders of this project.we want only the
play and stop images to appear in the ToggeButton without text, we need to reset the android:textOn and
android:textOff attributes of the <ToggleButton> tag in the layout file main.xml, as
android:textOn="" android:textOff=""
VISVODAYA ENGINEERING COLLEGE, KAVALI 23
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Also, we need to use the android:background attribute to display the play.png image in the
ToggleButton on startup. After we apply these modifications, the layout file appears as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width= "match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"
android:gravity="center" />
<ToggleButton
android:id="@+id/playstop_btn"
android:layout_width= "wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textOn=""
android:textOff=""
android:background="@drawable/play" />
</LinearLayout>
To change the background image of the ToggleButton from play.png to stop.png when clicked, we
need to add two statements to the Java activity file PlayAudioAppActivity. Java. Add
playStopButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.stop));
in if statement and
playStopButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.stop));
in else statement.
After the application is run, we see the Textview and a ToggleButton showing the play.png image
(left). The text in the Textview control tells the user that when the Play button is clicked, an audio file is
played. The audio begins playing, and the ToggleButton's background changes from play.png to
stop.png. The text in Textview also changes to tell the user that the stop button can be pressed to stop the
audio (right).
Fig: (left) The Textview and a Toggle Button control representing an audio play button—audio plays when
selecting the ToggleButton, and (right) the ToggleButton's image changes to a Stop button when selected,
informing the user that audio stops if selected again.
VISVODAYA ENGINEERING COLLEGE, KAVALI 24
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Playing Video
To play video in an application, Android provides a videoview control, which, along with the
MediaController, provides several buttons for controlling video play. These buttons allow us to play,
pause, rewind, and fast-forward the video content displayed via the videoview control.
To understand the steps for playing a video, let's create a new Android project called
playvideoApp.
Loading Video onto an SD Card
An emulator must be running while loading video onto an sd card. Switch on the emulator by
selecting the window, AVD Manager option. Select the demo AVD virtual device and select the start
button. Select the launch button to run the emulator. Remember only the emulator with an sd card option
should be run.
To load a video on to an sd card, follow these steps:
1. Open the DDMS perspective by selecting the window, open perspective, DDMS option.
2. In the DDMS perspective, open the file explorer by selecting window, show view, file
explorer.
3. If you can’t see the running emulator anywhere, open the devices view by selecting
window, show view, devices option. We are able to see all the running emulators, and we
can select the one that we want to use for playing the video.
4. In the file explorer view, see different folders and files in the emulator.
Click the button push a file onto the device. We see a dialog box for choosing a video from disk
drive. After selecting the video, select the ok button to load the selected video onto the sd card.
Now we can add a videoview control to our layout file to view the loaded video. After we define
the VideoView and Button Controls in activity_play_video_app. xml, it appear as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width= "match_parent"
android:layout_height="match_parent" >
<VideoView android:id="@+id/video"
android:layout_width="320dip"
android:layout_height="420dip" />
<Button android:id="@+id/playvideo"
android:text="Play Video"
android:layout_height="wrap_content"
android:layout_width="match_parent" />
</LinearLayout>
To assign the video to the videoview control, which is used to perform a variety of functions, write
the code in PlayVideoAppActivity.java as
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.VideoView;
VISVODAYA ENGINEERING COLLEGE, KAVALI 25
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
import android.widget.MediaController;
import android.view.View;
import android.view.View.OnClickListener;
public class PlayVideoAppActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_video_app);
Button playVideoButton =(Button)findViewById(R.id.playvideo);
playVideoButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
VideoView videoView =(VideoView)findViewById(R.id.video);
videoView.setMediaController(new MediaController(MainActivity.this));
videoView.setVideoPath("sdcard/video.mp4");
videoView.requestFocus();
videoView.start();
}
});
}
}
The videoview object is used for displaying video content and the button controls that enable us to
perform play, pause, rewind, or fast-forward actions on the video. A MediaController provides these
buttons. Run the application. We get the output showing a button, play video, as shown in Fig (left).
After we select the Play video button, the video is displayed in the videoview control, along with the
button controls displayed via the MediaController, as shown in Fig (right). The buttons enable stop,
resume, rewind, and fast-forward. The progress bar at the bottom shows our location in the video.
Fig: (left) The button control with the caption, Play video, displayed on application startup, and (right) the
video displayed in the videoview control on selecting the Play video button. Video control buttons appear at
the bottom via the MediaController.
VISVODAYA ENGINEERING COLLEGE, KAVALI 26
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Displaying Progress with ProgressBar
Certain tasks, such as downloading a file, installing software, executing complex queries, and
playing audio and video, take time to execute. While executing such tasks, we need to continually
inform the user about the task progress by displaying a progress indicator.
The ProgressBar is a control commonly used for displaying the progress of execution of tasks. To
make the ProgressBar display in the form of a horizontal bar, set its style attribute to
@android:style/Widget.ProgressBar.Horizontal, as shown in this example:
<ProgressBar android:id="@+id/progressbar"
android:layout_width="match_parent"
android: layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Horizontal" />
The following styles can be applied to the ProgressBar:
►widget.ProgressBar.Horizontal
►Widget.ProgressBar.Small
►widget.ProgressBar.Large
►Widget.ProgressBar.Inverse
►widget.ProgressBar.Small.Inverse
►Widget.ProgressBar.Large.Inverse
Fig: (left) Horizontal style ProgressBar, (middle) small style ProgressBar, and (right) large style ProgressBar.
The inverse style is used when our application uses a light-colored theme, such as a white
background. The minimum value of the ProgressBar is by default 0. The maximum value of the
ProgressBar is set by the android:max attribute. For example, the following statement, when applied to
the ProgressBar control in the layout file, sets the maximum value Of the ProgressBar to 100:
android:max="100"
We can also set the maximum value of the ProgressBar through a setMax Java method. The
following code sets the maximum value of the ProgressBar to 100:
progressBar.setMax(100);
Create an Android project to understand the ProgressBar. Name the new Android project
ProgressBarApp. In this application, we play an audio, and the ProgressBar displays the progress of the
audio. The layout file activity_progress_bar_app.xml appears as
<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" >
VISVODAYA ENGINEERING COLLEGE, KAVALI 27
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<TextView
android:layout_width="match_parent"
android:layout_height ="wrap_content"
android:gravity="center"
android:id="@+id/response" />
<ToggleButton android:id="@+id/playstop_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn=""
android:textoff =""
android:layout_gravity="center"
android:background="@drawable/play" />
<ProgressBar android:id="@+id/progressbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_marginTop="20dip" />
</LinearLayout>
To play and stop the audio with the ToggleButton control and to display the progress of the audio
in the ProgressBar control, Write the code in the activity file ProgressBarAppActivity. java.
import android.app.Activity;
import android.os.Bundle;
import android.widget.ToggleButton;
import android.widget.TextView;
import android.widget.ProgressBar;
import android.view.View;
import android.media.MediaPlayer;
import android.view.View.OnClickListener;
import android.os.Handler;
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView response = (TextView)this.findViewById(R.id.response);
response.setText("Select Play button to play audio");
progressBar=(ProgressBar)findViewById(R.id.progressbar);
mp = MediaPlayer.create(ProgressBarAppActivity.this,R.raw.song1);
final ToggleButton playStopButton = (ToggleButton)
findViewById(R.id.playstop_btn);
progressBar.setProgress(0);
progressBar.setMax(mp.getDuration());
playStopButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (playStopButton.isChecked()) {
response.setText("Select Stop button to stop audio");
playStopButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.stop));
mp.start();
updateProgressBar();
VISVODAYA ENGINEERING COLLEGE, KAVALI 28
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
}
else {
response.setText("Select Play button to play audio");
playStopButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.play));
mp.pause();
}
}
});
}
private void updateProgressBar(){
progressBar.setProgress(mp.getCurrentPosition());
if (mp.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
updateProgressBar();
}
};
handler.postDelayed(notification,1000);
}
}
}
After the user selects the ToggleButton, the audio begins playing, and the image on the
ToggleButton changes to display the stop.png file, and the text displayed through the Textview changes
to select stop button to stop audio. The indicator in the ProgressBar shows the duration of the audio
played, as
Fig: (left) ProgressBar on application Startup, and (right) ProgressBar showing the duration of audio played.
Using Assets
Besides the res/ directory, Android provides another directory, assets/, where we can keep asset
files to be included in our application. The difference between resources and assets is that the resources
are accessible in an Android application through the resource IDs generated in the r. java file.
Content placed in the assets/ directory is maintained in raw file format, and no IDs are generated
for these files. To read the content from the assets/ folder in an Android application, use the
AssetManager, which reads the content from the external files in the form of a stream of bytes.
In the application that are going to create as an example, add a text file asset. The content in the
text file added to the assets folder is accessed using the AssetManager and is displayed in a TextView.
VISVODAYA ENGINEERING COLLEGE, KAVALI 29
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Add a file called info.txt (it should obviously contain some text) to the project by copying and
pasting it into the assets folder in the package Explorer window. Modify the layout file
activity_assets_app.xml to appear as
<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" >
<TextView
android:id="@+id/file_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dip"
android:textStyle="bold" />
</LinearLayout>
To read the content from the file, info.txt is placed in the assets folder and is displayed via the
Textview control. The code written in the Java activity file AssetsAppActivity. java for reading the
content from the file placed in the assets folder and displaying it through the Textview control.
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.InputStream;
import android.content.res.AssetManager;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assets_app);
TextView fileView=(TextView)findViewById(R.id.file_view);
InputStream input;
AssetManager assetManager = getAssets();
try {
input = assetManager.open("info.txt") ;
int fileSize = input.available();
byte[] buffer = new byte[fileSize];
input.read(buffer);
input.close();
String textForm = new String(buffer);
fileView.setText(textForm);
} catch (IOException e) {
fileView.setText("Some exception has occurred");
}
}
}
VISVODAYA ENGINEERING COLLEGE, KAVALI 30
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
After the application is run, we find the content of the file info.txt is displayed through Textview, as
Fig: The content of the file in the assets folder displayed via Textview
VISVODAYA ENGINEERING COLLEGE, KAVALI 31
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
UNIT-IV
CHAPTER-I
USING SELECTION WIDGETS AND DEBUGGING
Using ListView
A Listview is used to display a list of vertically scrolling items, allowing users to select one or
more of them. Several attributes can be used to configure this control. Several attributes can be used to
configure this control. Some of them are
Attribute Description
android:entries Used to refer to an array resource for displaying options in the Listview
android:choiceMode Used to define the number of items that are selectable from the Listview.
Valid values are none—Doesn't allow selection of any option from the
Listview. singleChoice—Allows selection of a single option from the
Listview. multipleChoice—Allows selection of more than one option from
the Listview
multipleChoiceModal Used to allow selection of more than one item in a custom selection mode.
android:drawSelectorOnTop When set to true, the selector is drawn over the selected item.
Otherwise, the selector is drawn behind the selected item.
android:transcriptMode The transcript mode helps in deciding whether we want the list to
automatically scroll to the bottom. The valid values are disabled—Disables
the transcript mode. normal—The Listview automatically scrolls to the
bottom when a new item is added to the adapter and a notification is
generated. alwaysScroll—The Listview always automatically scrolls.
A sample Listview control may appear as follows:
<ListView
android:id="@android:id/list"
android:layout_width= "match_parent"
android:layout_height="match_parent"
android:entries="@array/fruits"
android:choiceMode="singleChoice"
android:drawSelectorOnTop="false"
android:transcriptMode="normal" />
This defines a Listview with the ID list, whose items are populated by the string array fruits. Only
one item is selectable from the Listview. No selector appears on the top of the Listview and it also
scrolls to the bottom when a new item is added to the data source.
For creating Listview controls, use either of the following methods:
The regular Activity base class.
An activity that extends android. app. ListActivity.
VISVODAYA ENGINEERING COLLEGE, KAVALI 1
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Creating a Listview with an Activity Base Class
The Listview can be populated by one of the following two methods:
By Listview through a string resource.
By Listview through Adapter.
Populating Listview Through String Resource
The item or option selected from the Listview is displayed via the Textview control. Open the
String resource file /res/values/strings.xml, and add a string-array structure called fruits that lists various
fruits that we want to display via the Listview control.
After we add a string-array, the strings.xml file appears as
<resources>
<string name="app_name">ListViewApp</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_list_view_app">ListViewAppActivity</string>
<string-array name="fruits">
<item>Apple</item>
<item>Mango</item>
<item>orange</item>
<item>Grapes</item>
<item>Banana</item>
</string-array>
</resources>
After we define fruits, the next step is to define the two controls, Listview and Textview, in the
layout file. The code written into activity_list_view_app .xml appears as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools= "http://schemas.android.com/tools"
android:orientation= "vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Listview android:id="@+id/fruits_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="@array/fruits"
android:drawSelectorOnTop="false"/>
<TextView
android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
To display the option selected from the Listview in the Textview control, we need to access the
string-array Textview and attach an event listener to the Listview to sense for the occurrence of an event
on it. We write the code in Java activity file ListviewAppActivity. java as
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.ListView;
import android.widget.AdapterView;
VISVODAYA ENGINEERING COLLEGE, KAVALI 2
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
import android.widget.AdapterView.OnItemClickListener;
import android.view.View;
public class ListViewApp extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_app);
final String[] fruitsArray = getResources().getStringArray(R.array.fruits);
final TextView selectedOpt=(TextView)findViewById(R.id.selectedopt);
ListView fruitsList = (ListView)findViewById(R.id.fruits_list);
fruitsList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,long id)
{
selectedOpt.setText("You have selected "+fruitsArray[position]);
}
});
}
}
When the application is run, we see the output as
Fig: Options displayed via the string array (string resource) in the Listview control (left) and the selected
option from Listview (right) displayed via the Textview control
Another way to display items through Listview is to use Adapters.
Adapters
Android provides a framework of adapters (also known as data adapters) that are used to provide a
data source for displaying content in the form of choices in selection widgets.
The data source refers to the content, including elements in arrays and data in database tables.
The Adapters serve two purposes.
First, they provide the data source for a selection widget, and
Second, they convert individual elements of data into specific views to be displayed inside
the selection widget. Android provides many basic Adapters such as ListAdapter, ArrayAdapter,
and CursorAdapter. We use the ArrayAdapter for populating selection widgets.
VISVODAYA ENGINEERING COLLEGE, KAVALI 3
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Populating Listview Through the ArrayAdapter
To create an ArrayAdapter and use it to populate the Listview control. An ArrayAdapter can be
created through string resource, as well as through string arrays defined in Java code.
Create a new Android project called ListviewDemo1. Again, in this application, we use two
controls, Listview and Textview, where Listview displays the items assigned to it through ArrayAdapter
and the Textview displays the item that is selected by the user from the Listview.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width= "match_parent"
android:layout_height="wrap_content">
<ListView
android:id="@+id/fruits_list"
android:layout_width="match_parent"
android:layout_height="match_parent“
android:drawSelectorOnTop="false"/>
<TextView
android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout >
Write code into the Java activity file to serve the following purposes:
Create an ArrayAdapter through a string array and assign it to the Listview for displaying items
Display the item selected from the Listview in the Textview.
The code written into the activity file ListviewDemo1Activity. java is
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.view.View;
public class ListViewDemo1Activity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_demo1);
final String[] fruits={"Apple", "Mango", "Orange", "Grapes", "Banana"};
final TextView selectedOpt=(TextView)findViewById(R.id.selectedopt);
ListView fruitsList = (ListView)findViewById(R.id.fruits_list);
final ArrayAdapter<String> arrayAdpt= new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, fruits);
fruitsList.setAdapter(arrayAdpt);
fruitsList.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,long id){
VISVODAYA ENGINEERING COLLEGE, KAVALI 4
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
selectedOpt.setText("You have selected "+fruits[position]);
}
});
}
}
An ArrayAdapter makes use of the Textview control to represent the child views in a view. In the
above code shown, an ArrayAdapter is created through the following code:
ArrayAdapter<String> arrayAdpt= new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,fruits);
This constructor creates an ArrayAdapter called arrayAdpt that can display the elements of the
specified array, fruits, via the Textview control.The constructor consists of the following:
this (the current context)—As the Activity is an extension of the context class, we use the current
instance as the context.
android.R.layout.simple_list_item_1—Points to a Textview defined by the Android SDK that
will be used for displaying each item in the Listview. This simply turns the strings defined in the
string array into a Textview for displaying them in a Listview.
array—The data source—an array of strings for the Listview.
When we run the application, the list of items is displayed via Listview, and the item
selected from the Listview is displayed via the Textview control, as
Fig:Options displayed through Java code in the Listview control and the selected option from Listview
displayed through the Textview control.
Creating Listview by Extending ListActivity
As ListActivity automatically constructs a full-screen list for us. Also there is no need of using the
onCreate() method for defining the content view of the activity for the simple reason that ListActivity
already contains a Listview control.
Let's create a new application to examine the creation of Listview by extending the ListActivity
class. Name the new application ListviewDemo2. We want to display Listview and Textview controls in
our application, we need to use the layout file activity_list_view_demo2 .xml and write the code as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
VISVODAYA ENGINEERING COLLEGE, KAVALI 5
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:layout_width= "match_parent"
android:layout_height ="wrap_content">
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false" />
<TextView
android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
The ID assigned to the Listview control defined in xml must be @android:id/list; otherwise,
ListActivity will not be able to identify it.To populate Listview and to display the item selected from it
through the Textview control, write the code in ListviewDemo2Activity. java as
import android.os.Bundle;
import android.app.ListActivity;
import android.widget.TextView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.View;
public class ListViewDemo2Activity extends ListActivity {
TextView selectedOpt;
String[] fruits={"Apple","Mango","Orange","Grapes","Banana"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_demo2);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
ArrayAdapter<String> arrayAdpt = new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice,fruits); #1
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); #2
setListAdapter(arrayAdpt);
}
@Override
public void onListItemClick(ListView parent, View v, int position, long id) {
super.onListItemClick(parent, v, position, id);
selectedOpt.setText("You have selected "+fruits[position]);
}
}
To enable users to select multiple items from the Listview, replace simpie_list_item_single_choice
with simple_list_item_multiple_choice in statement #1 and change the choice mode in statement #2
from Listview.choice_mode_single to Listview.choice_mode_multiple. After we make these two
changes, the statements appear as shown here:
ArrayAdapter<String> arrayAdpt = new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,fruits);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
VISVODAYA ENGINEERING COLLEGE, KAVALI 6
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
On running the application, we find
Fig: The Listview control with the choice mode set to single (left), and the Listview control with the choice
mode set to multiple (right)
Using the Spinner Control
The spinner is akin to a drop-down list that displays a list of items, allowing the user to select the
desired item. After the user touches a Spinner or presses the center button of the D-pad, a list of items is
displayed, allowing the user to select an item from the list.
Populating a spinner Through Resources
Define two resources, one to display a prompt in the spinner control and the other to display a list
of choices. To display a prompt in the spinner control, define a string resource.
STRINGS.XML
<resources>
<string name="app_name">SpinnerApp</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_spinner_app">SpinnerAppActivity</string>
<string name="choose_msg">Choose a Fruit</string>
</resources>
To add a new xml file to the res/ values folder, right-click on the res/values folder in the Package
Explorer window and select the New, Android xml File option. Call the file arrays (without the
extension .xml) and then click the Finish button. The code written in arrays .xml is
ARRAYS.XML
<resources>
<string-array name="fruits">
<item>Apple</item>
<item>Mango</item>
<item>Banana</item>
<item>Orange</item>
<item>Grapes</item>
</string-array>
</resources>
VISVODAYA ENGINEERING COLLEGE, KAVALI 7
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
To display the spinner control in the application, let's define it in the layout file
activity_spinner_app.xml, as
<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">
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/choose_msg"
android:entries="@array/fruits"/>
<TextView
android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
The prompt attribute is a string that appears at the top of the spinner control to guide the user. We
want the item selected from the spinner control by the user to appear in the Textview. To do so, write the
code in the Java activity file SpinnerAppActivity.java.
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Spinner;
import android.widget.AdapterView;
import android.view.View;
import android.widget.AdapterView.OnItemSelectedListener;
public class SpinnerAppActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_app);
final TextView selectedOpt=(TextView)findViewById(R.id.selectedopt);
Spinner spin=(Spinner)findViewById(R.id.spinner);
final String[] fruitsArray = getResources().getStringArray(R.array.fruits);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedOpt.setText("You have selected " + fruitsArray[position]);
} @Override
public void onNothingSelected(AdapterView<?> parent) {
selectedOpt.setText(" ");
}
});
}
}
VISVODAYA ENGINEERING COLLEGE, KAVALI 8
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
When we run the application, the spinner and Textview control appear as
Fig: spinner control with a drop-down arrow (left), options displayed through an Arrays Resource in the
spinner control (middle), and the option selected in the spinner displayed through Textview (right)
Populating a Spinner Through ArrayAdapter
Before populating the spinner control with ArrayAdapter, we make it empty by removing the
android:entries="@array/fruits" attribute from the XML definition of the Spinner control in the layout
file main.xml.After we remove the entries attribute from the spinner control, the layout file appears as
<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">
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/choose_msg"/>
<TextView
android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
There is no need to make any changes to strings.xml, the resource file, and we don't need the
arrays.xml file either. To create an ArrayAdapter and to assign it to the spinner control for populating it,
the code written in the Java activity file is
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.view.View;
import android.widget.AdapterView.OnItemSelectedListener;
VISVODAYA ENGINEERING COLLEGE, KAVALI 9
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
public class SpinnerAppActivitty extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView selectedOpt=(TextView)findViewById(R.id.selectedopt);
final String[] fruits={"Apple","Mango","Orange","Grapes","Banana"};
Spinner spin=(Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> arrayAdpt=new
spin.setAdapter(arrayAdpt);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
selectedOpt.setText("You have selected " +fruits[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
selectedOpt.setText("");
}
});
}
}
After we select the drop-down arrow of the spinner control, the items listed in the spinner control
are displayed as
Fig: spinner control with a drop-down arrow (left), options displayed in the spinner control via Java code
(middle), and the selected option displayed through the Textview (right)
AutoCompleteTextView
The AutoCompleteTextView control is an EditText control with auto-complete functionality. As
the user types, suggestions based on the entered characters appear. The user can select any of the
displayed suggestions to fill in the EditText control.
To implement the auto-complete facility, we create an ArrayAdapter and set it to display items or
suggestions from a data source, preferably an array, and wrap them in a view, called something like
simple_list_item_1 or simple_dropdown_item_1.
The code written in the layout file activity_ auto_complete_app.xml, as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
VISVODAYA ENGINEERING COLLEGE, KAVALI 10
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<TextView
android:text="Enter product name:"
android:layout_width= "match_parent"
android:layout_height="wrap_content" />
<AutoCompleteTextView
android:id="@+id/product_names"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
To display a list of suggestions, we need to create an ArrayAdapter and associate it with
AutoCompleteTextview. To do so, the code written in the AutoCompleteAppActivity. java file as
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class AutoCompleteAppActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
String[] products ={"Camera","Handi Cam","Cell phone","Laptop","Car"};
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_complete_app);
ArrayAdapter<String> arrayAdapt = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, products);
AutoCompleteTextView productNames = (AutoCompleteTextView)
findViewById(R.id.product_names);
productNames.setThreshold(1);
productNames.setAdapter(arrayAdapt);
}
}
The setThreshold () method is used to indicate the minimum number of characters that a user must
enter before the suggestions are displayed. On running the application, we get a Textview and an
AutoCompleteTextView control on startup.
Fig: The Textview and the AutoCompleteTextView displayed on application startup (left), possible options
displayed (middle) based on the characters that are typed, and available result after l is entered (right)
VISVODAYA ENGINEERING COLLEGE, KAVALI 11
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Using the Gridview Control
The Gridview control is a viewGroup used to display text and image data in the form of a
rectangular, scrollable grid. To display data in the grid, we first define a Gridview control in the XML
layout, and then bind the data that we want to be displayed to it using the ArrayAdapter.
ViewGroup is a view that contains other views known as child views. The viewGroup class is a
base class for layout managers that are used to contain and arrange several views. Listview, Gridview,
and other container controls are good examples of viewGroups.
Let's create a new Android project called GridviewApp. In this application, we display certain
strings arranged in a rectangular grid. When a user selects any of the strings, its name is displayed. We
write the code in the activity_grid_view_app.xml layout file as
<LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select a fruit " />
<GridView
android:id="@+id/grid"
android:layout_width="match_parent"
android:layout_height ="match_parent"
android:verticalSpacing="2dip"
android:horizontalSpacing="5dip"
android:numColumns="auto_fit"
android:columnWidth="130dip"
android:stretchMode="columnWidth"
android:gravity="center" />
</LinearLayout >
Gridview Attributes
The number of rows displayed through Gridview is dependent on the number of elements supplied
by the attached adapter. The size and number of columns is controlled through the following attributes:
android:numColumns—Defines the number of columns. If we supply a value, auto_ fit, Android
computes the number of columns based on available space.
android:verticalSpacing and android:horizontalSpacing—Define the amount of whitespace
between the items in the grid.
android:columnwidth—Defines the width of each column.
android:stretchMode—This determines whether the column can stretch or expand to take up the
available space.The valid values are columnwidth—Makes the columns take up all available space.
spacingwidth— Makes the whitespace between columns take up all available space.
none—Does not allow columns to stretch or expand.
VISVODAYA ENGINEERING COLLEGE, KAVALI 12
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
To display content in the Gridview and to display the item selected from the Gridview in
Textview, write the code shown in Listing 5.17 into the Java activity file GridviewAppActivity.java.
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.GridView;
import android.widget .ArrayAdapter;
import android.widget.AdapterView;
import android.view.View;
public class GridViewAppActivity extends Activity implements
AdapterView.OnItemClickListener {
TextView selectedOpt;
String[] fruits={"Apple", "Mango", "Banana", "Grapes", "Orange","Pineapple",
"Strawberry", "Papaya", "Guava", "Pomegranate", "Watermelon", "Chickoo",
"Dates", "Plum", "Cherry", "Kiwi"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
GridView g=(GridView)findViewById(R.id.grid);
ArrayAdapter<String>arrayAdpt=new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,fruits);
g.setAdapter(arrayAdpt);
g.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
selectedOpt.setText("You have selected "+fruits[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
selectedOpt.setText ("");
}
}
If we reduce the size of the column width in the Gridview definition, we can accommodate more
columns. For example, modifying the attribute shown accommodates three columns in the Gridview:
android:columnWidth ="100dip"
Fig: Items displayed in two columns in Gridview (left), and items displayed in three Columns in GridView (right)
VISVODAYA ENGINEERING COLLEGE, KAVALI 13
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Displaying Images in GridView
To create our own custom adapter and subsequently use it to display images in the Gridview
control. Let's create a new application called GridImageApp. Assuming the image filenames that want to
display through the Gridview control are prod1.png, prod2.png, prod3.png, prod4.png, and prod5.png,
copy them into the res/drawable folders.
<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/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="List of Products " />
<GridView android:id="@+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="2dip"
android:horizontalSpacing="2dip"
android:numColumns= "auto_fit"
android:columnWidth="100dip"
android:stretchMode="columnWidth"
android:gravity="center" />
</LinearLayout>
To display images in the Gridview control and also tell us which image is selected by the user,
write the code in activity file GridimageAppActivity.java.
import android.content.Context;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
public class GridimageAppActivity extends Activity implements
AdapterView.OnItemClickListener {
TextView selectedOpt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedOpt=(TextView) findViewById(R.id.selectedopt);
GridView g=(GridView) findViewById(R.id.grid);
g.setAdapter(new ImageAdapter(this));
g.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
int p=position+1;
VISVODAYA ENGINEERING COLLEGE, KAVALI 14
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
selectedOpt.setText("You have selected the image number "+p);
}
public class ImageAdapter extends BaseAdapter {
private Context contxt;
Integer[] images = { R.drawable.prod1, R.drawable.prod2, R.drawable.prod3,
R.drawable.prod4, R.drawable.prod5};
public ImageAdapter(Context c) {
contxt = c;
}
public int getCount(){
return images.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageview = new ImageView(contxt);
imageview.setImageResource(images[position]);
imageview.setLayoutParams(new GridView.LayoutParams(100,120));
return imageview;
}
}
}
On running the application, we see that all images are displayed in Gridview, as
Fig: Images displayed in a Gridview control (left), and the selected image number displayed via a Textview (right)
Creating an Image Gallery Using the ViewPager Control
The ViewPager control (android, support.v4.view.ViewPager) helps in showing data, which may
be text, image, and so on, in the form of pages with the horizontal swiping behaviour. That is, the pages
of data being displayed can be flipped left and right. To identify and to keep track of the pages being
displayed through ViewPager, a key object is associated with each of them.
The ViewPager needs a data adapter to define and load the data for each page. The data adapter
that is used to define the data for each page to be displayed through the ViewPager control is the
PagerAdapter (android. support. v4. view. PagerAdapter) class.
VISVODAYA ENGINEERING COLLEGE, KAVALI 15
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
While implementing the PagerAdapter, must override the following methods:
instantiateltem(View container, int position)—Used for Creating and instantiating the page and
adding it to the container.
Syntax: public ObjectinstantiateItem(View container, int position)
container—Represents the container in which the page has to be displayed.
position—Represents the position of the page to be instantiated.
destroyItem(View container, int position,Object object)—Used for removing the page of the
specified position from the container.
isviewFromobject(view view, object object)—Determines whether the specified page is
associated with a specific key object.
getCount()—Defines the size of the paging range, that is, the count of the number of the pages.
The position of the pages is zero based by default; that is, the first page to the left is in position 0,
the next page to the right is position 1, and so on. The first step is to copy the images that we want to
display through the gallery into the res/drawable folders of the application.
The viewPager control displays the images in a horizontally scrolling list. After we define the
Textview and viewPager control, activity_view_pager_app.xml appears as
<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" >
<TextView android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Image Gallery"
android:gravity="center"
android:textStyle="bold" />
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="100dip"
android:layout_marginTop="25dip" />
</LinearLayout>
To display images in the viewPager control and to display the image number selected by the user,
write into the activity file ViewPagerAppActivity.java.
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.PagerAdapter;
import android.widget.TextView;
import android.view.View;
import android.widget.ImageView;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
VISVODAYA ENGINEERING COLLEGE, KAVALI 16
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
public class ViewPagerAppActivity extends Activity {
TextView selectedOpt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedOpt = (TextView) findViewById(R.id.selectedopt);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new ImageAdapter());
viewPager.setOnPageChangeListener(new PageListener());
}
public class ImageAdapter extends PagerAdapter {
Integer[] images = {R.drawable.prod1, R.drawable.prod2, R.drawable.prod3,
R.drawable.prod4, R.drawable.prod5};
public Object instantiateItem(View container, int position) {
ImageView view = new ImageView(ViewPagerAppActivity.this);
view.setImageResource(images[position]);
((ViewPager) container).addView(view, 0);
return view;
}
@Override
public int getCount() {
return images.length;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
}
private class PageListener extends SimpleOnPageChangeListener {
public void onPageSelected(int position) {
selectedOpt.setText("You have selected the page number " + position);
}
}
}
On running the application, we find that all images are displayed through the ViewPager, as
shown in Fig. When we select an image from the gallery, its position is displayed on the screen.
VISVODAYA ENGINEERING COLLEGE, KAVALI 17
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Using the Debugging Tool: Dalvik Debug Monitor Service (DDMS)
VISVODAYA ENGINEERING COLLEGE, KAVALI 18
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
UNIT-IV
CHAPTER-II
DISPLAYING AND FETCHING INFORMATION USING DIALOGS
AND FRAGMENTS
What Are Dialogs?
We usually create a new activity or screen for interacting with users, but when we want only a
little information, or want to display an essential message, dialogs are preferred. Dialogs are also used to
guide users in providing requested information, confirming certain actions, and displaying warnings or
error messages. The following are different dialog window types provided by the Android SDK:
Dialog—The basic class for all dialog types.
AlertDialog—A dialog with one, two, or three Button controls.
CharacterPickerDialog—A dialog that enables you to select an accented character associated
with a regular character source.
DatePickerDialog—A dialog that enables you to set and select a date with a DatePicker control.
ProgressDialog—A dialog that displays a ProgressBar control showing the progress of a
designated operation.
TimePickerDialog—A dialog that enables you to set and select a time with a TimePicker control.
A dialog is created by creating an instance of the Dialog class. The Dialog class creates a dialog in
the form of a floating window containing messages and controls for user interaction.
If the dialog is open, users can interact only with the options and controls in the dialog until it is
closed. While the user interacts with the dialog, the parent activity resumes its normal execution for
efficiency.
Each dialog window is defined within the activity where it will be used. A dialog window can be
created once and displayed several times. It can also be updated dynamically.
The following is a list of the Activity class dialog methods:
showDialog()—Displays a dialog and creates a dialog if one does not exist. Each dialog has a
special dialog identifier that is passed to this method as a parameter.
onCreateDialog()—The callback method that executes when the dialog is created for the first
time. It returns the dialog of the specified type.
onPrepareDialog()—The callback method used for updating a dialog.
dismissDialog()— Closes the dialog whose dialog identifier is supplied to this method. The dialog
can be displayed again through the showDialog() method.
removeDialog()—The dismissDialog() method doesn't destroy a dialog. The dismissed dialog can
be redisplayed from the cache. If we do not want to display a dialog, we can remove it from the
activity dialog pool by passing its dialog identifier to the removeDialog() method.
VISVODAYA ENGINEERING COLLEGE, KAVALI 1
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
The onCreateDialog() method is called only once while creating the dialog for the first time,
whereas the onPrepareDialog() method is called each time the showDialog() method is called, allowing
the activity to update the dialog before displaying it to the user.
By overriding the onCreateDialog method, we specify dialogs that will be created when
showDialog() is called. Several dialog window types are available in the Android SDK, such as
AlertDialog, DatePickerDialog, and TimePickerDialog, that we can readily use in an application. All the
dialog windows are created by extending the Dialog class.
AlertDialog
An AlertDialog is a popular method of getting feedback from the user. This pop-up dialog remains
there until closed by the user and hence is used for showing critical messages that need immediate
attention or to get essential feedback before proceeding further.
The simplest way to construct an AlertDialog is to use the static inner class AlertDialog. Builder
that offers a series of methods to configure an AlertDialog. This example creates a new
AlertDialog.Builder Object called alertDialog:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
In this example, this refers to the context, that is, the current activity created here. We can add a
title, icon, and message to the alertDialog object that we want to display in the dialog. We can define
buttons and controls for user interaction to display in the dialog. We can also register event listeners with
the dialog buttons for handling events.
Methods of the AlertDialog.Builder Subclass
The methods of the AlertDialog.Builder subclass that can use to configure the AlertDialog box are
setTitle() and setIcon()—For specifying the text and icon to appear in the title bar of the dialog
box.
setMessage()—For displaying a text message in the dialog box.
setPositiveButton(), setNeutralButton(), and setNegativeButton()—
For configuring the following three buttons:
Positive button—Represents the ok button.
Negative button—Represents the cancel button.
Neutral button—Represents a button to perform a function other than ok or Cancel.
Through these three methods, we can set the three buttons to appear in the dialog and also define
their location in the dialog box.
Create an Android application, Name the project AlertDialogApp. In this application, we want to
display a Button control that, when clicked, displays the AlertDialog. So, first we need to define a
Button control in the layout file activity_alert_dialog_app.xml, as
<LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
VISVODAYA ENGINEERING COLLEGE, KAVALI 2
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:layout_height="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Click for Alert Dialog" />
</LinearLayout>
The dialog is built and shown on the screen through the Builder object. To do all this, the code in
the AlertDialogAppActivity. java is modified as
import android.app.Activity;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.View;
import android.app.AlertDialog;
import android.content.DialogInterface ;
public class AlertDialogAppActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alert_dialog_app);
Button b = (Button) this.findViewById(R.id.click_btn);
b.setOnClickListener(this);
}
@Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Alert window");
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setMessage("This is an alert");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int buttonId) {
return;
}});
alertDialog.show();
}
}
After running the application, we see
Fig: Button with the caption click for Alert Dialog displayed on application startup (left), and the AlertDialog
appears on selecting the Button control (right)
Getting Input via the Dialog Box
VISVODAYA ENGINEERING COLLEGE, KAVALI 3
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
We modify our current Android project AlertDialogApp to get input from the user. We make the
following changes to the application:
Dynamically create an EditText control and set it as part of the AlertDialog to prompt the user for
input.
Add a Textview control to the layout file to display the data entered by the user in AlertDialog.
To make it more specific, our application asks the user to input a name through AlertDialog, and
when the user selects the OK button after entering a name, a welcome message is displayed through the
Textview control defined in the layout file. We also add a cancel button to the AlertDialog, allowing the
user to cancel the operation, which terminates the dialog.
After Adding the Textview Control the Layout File activity_alert_dialog_app.xml, it appears as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Click for Alert Dialog"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>
Dynamically create an EditText control and set it as the content of the AlertDialog. Fetch the name
entered by the user in the EditText control and assign it to the Textview object for displaying a welcome
message. So, now modify the activity file as
import android.app.Activity;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
import android.app.AlertDialog;
import android.content.DialogInterface ;
public class AlertDialogAppActivity extends Activity implements OnClickListener {
TextView resp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alert_dialog_app);
resp = (TextView)this.findViewById(R.id.response);
Button b = (Button) this.findViewById(R.id.click_btn);
b.setOnClickListener(AlertDialogAppActivity.this);
}
VISVODAYA ENGINEERING COLLEGE, KAVALI 4
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
@Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Alert window");
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setMessage("Enter your name ");
final EditText username = new EditText(this);
alertDialog.setView(username);
alertDialog.setMessage("Enter your name");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int buttonId) {
String str = username.getText().toString();
resp.setText ("Welcome "+str+ "!");
return;
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int buttonld) {
return;
}
});
alertDialog.show();
}
}
After running the application, we see the output as
Fig: Getting input from the user via the AiertDiaiog (left), and the data entered by the user displayed through
Textview (right)
DatePickerDialog
DatePickerDialog is used to see and modify the date. Supply the day, month, and year values to its
constructor to initialize the date initially displayed through this dialog. The constructor includes a
callback listener to inform the current context when the date has been set or changed.
Create a new Android project and name it DatePickerApp. The application contains a Textview
and a Button control. When clicked, the Button control displays the DatePickerDialog, and the Textview
control displays the date set by the user.
Write the code in the layout file activity_date_picker_app.xml as
VISVODAYA ENGINEERING COLLEGE, KAVALI 5
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/datevw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button android:id="@+id/date_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set the Date" />
</LinearLayout>
We need to write some Java code into the activity file DatePickerAppActivity. java. The code in
the activity file does the following:
Access the system's current date through the calendar instance.
Display the current system date in the Textview control.
Display the DatePickerDialog, initialized to display the current system date when the Button
control is clicked.
Access the date set by the user in the DatePickerDialog when its Set button is clicked and display
it through the Textview control.
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import android.widget.DatePicker;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.view.View.OnClickListener;
import android.view.View;
public class DatePickerAppActivity extends Activity{
private TextView dispDate;
private int yr, mon, dy;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date_picker_app);
dispDate = (TextView) findViewById(R.id.datevw);
Button dateButton = (Button) findViewById(R.id.date_button);
final Calendar c = Calendar.getInstance();
yr = c.get(Calendar.YEAR);
mon = c.get(Calendar.MONTH);
dy = c.get(Calendar.DAY_OF_MONTH);
dispDate.setText("Current date is: "+(mon+1)+"-"+dy+"-"+yr);
dateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new DatePickerDialog(DatePickerAppActivity.this, dateListener, yr,mon, dy).show();
}
});
VISVODAYA ENGINEERING COLLEGE, KAVALI 6
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
}
private DatePickerDialog.OnDateSetListener dateListener = new
DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view,int year,int monthOfYear,int
dayOfMonth){
yr = year;
mon = monthOfYear;
dy = dayOfMonth;
dispDate.setText("Current date is: "+(mon+1)+"-"+dy+"-"+yr);
}
};
}
After running the application, we see the output as
Fig: A Textview displaying the current date with a Button control (top left); the DatePicker dialog after clicking
the Button control (top right); changing the day, month, and year displayed through the DatePicker dialog
(bottom left); and displaying the date selected from the DatePicker dialog in the Textview control (bottom
right)
VISVODAYA ENGINEERING COLLEGE, KAVALI 7
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
TimePickerDialog
The TimePickerDialog allows us to set or select time through the built-in Android TimePicker
view. We can set the values of hour and minute with values of hour ranging from 0 through 23 and
minutes from 0 through 59. When the Button control is clicked, the time picker dialog appears. To define
the TextView and Button, write the code in layout file,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/timevw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button android:id="@+id/date_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set the Time" />
</LinearLayout>
We need to write the code in the activity file TimePickerAppActivity. java to perform the
following tasks:
Invoke the TimePickerDialog when the button control is clicked.
Display the current system time in the TextView control.
Use the Calendar instance to initialize TimePickerDialog to display the current system time.
Display the newly set time in the TextView control.
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import android.widget.TimePicker;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.view.View.OnClickListener;
import android.view.View;
public class TimePickerAppActivity extends Activity{
private TextView dispTime;
private int h,m;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_picker_app);
dispTime = (TextView) findViewById(R.id.timevw);
Button dateButton = (Button) findViewById(R.id.date_button);
final Calendar c = Calendar.getInstance();
h=c.get(Calendar.HOUR_OF_DAY);
m=c.get(Calendar.MINUTE);
dispTime.setText("Current time is: "+h+":"+m);
dateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new TimePickerDialog(TimePickerAppActivity.this, timeListener,h,m,true).show();
VISVODAYA ENGINEERING COLLEGE, KAVALI 8
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
}
});
}
private TimePickerDialog.OnTimeSetListener timeListener = new
TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view,int hour,int minute){
h=hour;
m=minute;
dispTime.setText("Current time is: "+h+":"+m);
}
};
}
After running the application, we see the output as
Fig: The Textview displaying the current time with a Button control (top left), the TimePicker dialog appears
after selecting the Button control (top right), changing the hour and minutes displayed via the TimePicker
dialog (bottom left), and displaying the time selected from the TimePicker dialog in the Textview control
(bottom right)
VISVODAYA ENGINEERING COLLEGE, KAVALI 9
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Selecting the Date and Time in One Application
To see how the system date and time can be set in an application, let's create a new Android
application and name it DateTimePickerApp. In this application, we use a Textview and two Button
controls. The Textview control displays the current system date and time, and the two Button controls,
set Date and set Time, are used to invoke the respective dialogs.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/datetimevw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button android:id="@+id/date_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Set Date"/>
<Button android:id="@+id/time_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Set Time" />
</LinearLayout>
After defining the controls in the layout file, we write Java code into the
DateTimePickerAppActivity. java activity file to perform the following tasks:
Display the current system date and time in the Textview control.
Invoke DatePickerDialog and TimePickerDialog when the Set Date and Set Time Button controls
are clicked.
Initialize DatePickerDialog and TimePickerDialog to display the current system date and time via
the calendar instance.
Display the modified date and time set by the user via the DatePickerDialog and
TimePickerDialog through the Textview control.
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.TimePicker;
import android.widget.DatePicker;
public class DateTimePickerAppActivity extends Activity{
private TextView dateTimeView;
private Calendar c;
private int h,m,yr,mon,dy;
VISVODAYA ENGINEERING COLLEGE, KAVALI 10
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date_time_picker_app);
dateTimeView = (TextView) findViewById(R.id.datetimevw);
Button timeButton = (Button) findViewById(R.id.time_button);
Button dateButton = (Button) findViewById(R.id.date_button);
c = Calendar.getInstance();
h = c.get(Calendar.HOUR_OF_DAY);
m = c.get(Calendar.MINUTE);
yr = c.get(Calendar.YEAR);
mon = c.get(Calendar.MONTH);
dy = c.get(Calendar.DAY_OF_MONTH);
dateTimeView.setText("Current date is " + (mon + 1) + "-" + dy + "-" + yr + "
and current time is: " + h + ":" + m);
dateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new DatePickerDialog(DateTimePickerAppActivity.this, dateListener, yr,
mon, dy).show();
}
});
timeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new TimePickerDialog(DateTimePickerAppActivity.this, timeListener, h, m,
true).show();
}
});
}
private DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.
OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int
dayOfMonth) {
yr = year;
mon = monthOfYear;
dy = dayOfMonth;
dateTimeView.setText("Current date is "+ (mon+1)+"-"+dy+"-"+yr+" and
current time is: "+h+" :"+m) ;
}
};
private TimePickerDialog.OnTimeSetListener timeListener = new TimePickerDialog.
OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hour, int minute) {
h = hour;
m = minute;
dateTimeView.setText("Current date is "+ (mon+1)+"-"+dy+"-"+yr+" and
current time is: "+h+":"+m);
}
};
}
The respective listeners, onDateSetListener and OnTimeSetListener, invoke their callback
methods, onDateSet() and onTimeSet(), when the Done button in the DatePickerDialog or
TimePickerDialog is selected by the user. The two callback methods access the newly set date and time
and display them through the Textview control.
VISVODAYA ENGINEERING COLLEGE, KAVALI 11
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
After running the application,
Fig: The Textview displaying the current date and time and two Button controls (left), the DatePicker dialog appears when
the set Date button is clicked (middle), and the date selected from the DatePicker dialog displayed in the Textview (right)
Fig: The TimePicker dialog appears when the set Time button is clicked (left), changing the hour and minutes in the
TimePicker dialog (middle), and the time selected from the TimePicker dialog displayed in the Textview (right)
Fragments
The size of the screen changes when a device is oriented from portrait to landscape mode. When
developing an application, we need to arrange views in such a way that the user can view everything in
both landscape and portrait mode. If we don't organize the views with this in mind, problems arise if the
user switches modes while running an application.
One solution to this problem is one we have already seen—designing an individual layout for each
device or screen mode. This solution is time consuming. Another solution is implementing fragments in
the application.
VISVODAYA ENGINEERING COLLEGE, KAVALI 12
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
The Structure of a Fragment
A fragment is a combination of an activity and a layout and contains a set of views that
make up an independent and atomic user interface.
Let's assume that we have two fragments, Fragment1 and Fragment2, each having its own set of
views. If the screen size is small, we can create two activities, each having a single fragment, and display
one activity at a time. If the device screen is able to accommodate views of both Fragment1 and
Fragment2, these can be embedded into a single activity to fill up the screen.
To create a fragment, we need to extend the Fragment class and implement several life cycle
callback methods, similar to an activity.
The Life Cycle of a Fragment
The life cycle of a fragment includes several callback methods, as listed here:
onAttach ()—Called when the fragment is attached to the activity.
onCreate () —Called when creating the fragment. The method is used to initialize the items of the
fragment that we want to retain when the fragment is resumed after it is paused or stopped.
onCreateView ()—Called to create the view for the fragment.
onActivityCreated ()—Called when the activity's onCreate () method is returned.
onStart ()—Called when the fragment is visible to the user. This method is associated with the
activity's onStart ().
onResume ()—Called when the fragment is visible and is running. The method is associated with
the activity's onResume ().
onPause () —Called when the fragment is visible but does not have focus. The method is attached
to the activity's onPause ().
onStop()—Called when fragment is not visible. The method is associated with the activity's
onStop().
onDestroyView ()—Called when the fragment is supposed to be saved or destroyed. The view
hierarchy is removed from the fragment.
onDestroy ()—Called when the fragment is no longer in use. No view hierarchy is associated with
the fragment, but the fragment is still attached to the activity.
onDetach ()—Called when the fragment is detached from the activity and resources allocated to
the fragment are released.
Create an Android project called FragmentsApp. In this application, we are going to create two
fragments: Fragment1 and Fragment2. Fragment1 contains a selection widget, Listview, that displays a
couple of fruits to choose from. Fragment2 contains a Textview control to display the fruit selected from
the Listview of Fragment1. The fragments use individual XML layout files to define their views, so for
the two fragments, let's add two XML files called fragment1.xml and fragment2.xml to the res/layout
folder.
VISVODAYA ENGINEERING COLLEGE, KAVALI 13
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
To define a ListView control in the first fragment, the code written in the XML file, fragment1.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#0000FF" >
<ListView
android:id="@+id/fruits_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false" />
</LinearLayout>
For distinguishing the two fragments, the background of this fragment is set to blue. To define a
Textview control for the second fragment, the code written in the XML file fragment2.xml is
<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/selectedopt"
android:layout_width="match_parent"
android:layout_height= "wrap_content"
android:text="Please select a fruit" />
</LinearLayout>
Each fragment has a Java class that loads its UI from the XML file, so for the two fragments, we
need to add two Java classes to our application. Add FragmentlActivity.java and Fragment2Activity.java
to the com.androidunleashed.fragmentsapp package of the application.
The code written in the Java Class file of the first fragment, FragmentlActivity.Java is
import android.app.Fragment;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.View;
import android.view.LayoutInflater;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.content.Context;
import android.widget.AdapterView ;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
public class Fragment1Activity extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
Context c = getActivity().getApplicationContext ();
View vw = inflater.inflate(R.layout.fragment1, container, false);
final String[] fruits={"Apple", "Mango", "Orange", "Grapes", "Banana"};
ListView fruitsList = (ListView) vw.findViewById(R.id.fruits_list);
VISVODAYA ENGINEERING COLLEGE, KAVALI 14
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
ArrayAdapter<String> arrayAdpt= new ArrayAdapter<String>(c,
android.R.layout.simple_list_item_1, fruits);
fruitsList.setAdapter(arrayAdpt);
fruitsList.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
TextView selectedopt = (TextView) getActivity().findViewById(R.id.selectedopt);
selectedopt.setText("You have selected "+((TextView) v).getText().toString());
}
});
return vw;
}
}
To load the UI of the second fragment from the XML file fragment2 .xml, write the code in the
Java class file of the second fragment Fragment2Activity .java.
import android.app.Fragment;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.View;
import android.view.LayoutInflater;
public class Fragment2Activity extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
}
}
To accommodate both the fragments in the application, the code written into the layout file
activity_fragments_app.xml appears as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation= "horizontal" >
<fragment
android:name="com.androidunleashed.fragmentsapp.Fragment1Activity"
android:id="@+id/fragment1"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height ="match_parent" />
<fragment
android:name="com. androidunleashed.fragmentsapp.Fragment2Activity"
android:id="@+id/fragment2"
android:layout_weight="0"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
The fragments are set to refer to their respective Java class through the android: name attribute,
both the fragments appear beside each other.
VISVODAYA ENGINEERING COLLEGE, KAVALI 15
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
We don't have to write any code into FragmentsAppActivity. Java. We can leave the default code
unchanged, as
import android.app.Activity;
import android.os.Bundle;
public class FragmentsAppActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragments_app);
}
}
After we run the application, the two UIs defined in Fragment1 and Fragment2 appear side by side.
Fig: Listview and Textview controls displayed via two fragments (left), and the Textview of the second
fragment, showing the item selected from the Listview of the first fragment (right)
In the preceding example, we saw how two fragments were included in an activity. If we want only
the Listview control to appear when the device is in portrait mode. When an item is selected from the
Listview, the Textview should appear on the next screen in another activity. We also require that when
the device is in landscape mode, both controls, the Listview and the Textview, should appear beside each
other, as there will be enough space on the right.
We want only Fragment1 to be visible when the device is in portrait mode, let's remove Fragment2
from the layout file. After removing the layout file activity_fragments_app.xml appears as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation= "horizontal" >
<fragment
android:name="com. androidunleashed.fragmentsapp.Fragment1Activity"
android:id="@+id/fragment1"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height ="match_parent" />
</LinearLayout>
VISVODAYA ENGINEERING COLLEGE, KAVALI 16
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Because we want the UI of Fragment1 and Fragment2 to appear when the device is in landscape
mode, create a folder called layout-land in the res folder and copy the XML file. After we add two
fragments, the XML file appears as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation= "horizontal" >
<fragment
android:name="com.androidunleashed.fragmentsapp.Fragment1Activity"
android:id="@+id/fragment1"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height ="match_parent" />
<fragment
android:name="com. androidunleashed.fragmentsapp.Fragment2Activity"
android:id="@+id/fragment2"
android:layout_weight="0"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
Next, we need to modify the Java class of the Fragment1, Fragment1Activity to appear as
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.content.Intent;
import android.content.res.Configuration;
public class Fragment1Activity extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
Context c = getActivity().getApplicationContext ();
View vw = inflater.inflate(R.layout.fragment1, container, false);
final String[] fruits={"Apple", "Mango", "Orange", "Grapes", "Banana"};
ListView fruitsList = (ListView) vw.findViewById(R.id.fruits_list);
ArrayAdapter<String> arrayAdpt= new ArrayAdapter<String>(c,
android.R.layout.simple_list_item_1, fruits);
fruitsList.setAdapter(arrayAdpt);
fruitsList.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_LANDSCAPE) {
TextView selectedOpt = (TextView) getActivity().findViewById(R.id.selectedopt);
VISVODAYA ENGINEERING COLLEGE, KAVALI 17
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
selectedOpt.setText("You have selected " + ((TextView) v).getText().toString());
} else {
Intent intent = new Intent(getActivity().getApplicationContext(),ShowItemActivity.class);
intent.putExtra("item", ((TextView) v).getText().toString());
startActivity(intent);
}
}
});
return vw;
}
}
To start an activity, we need to first create a new intent specifying the current application context
and the class name of the activity that we want to launch, and pass this intent to the startActivity ()
method. Let's add a Java class called ShowItemActivity. java and write the content as
import android.app.Activity;
import android.os.Bundle;
import android.content.res.Configuration;
import android.widget.TextView;
public class ShowItemActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_LANDSCAPE) {
finish();
return;
}
setContentView(R.layout.fragment2);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String selectedItem = extras.getString("item");
TextView textview = (TextView) findViewById(R.id.selectedopt);
textview.setText("You have selected " + selectedItem);
}
}
}
VISVODAYA ENGINEERING COLLEGE, KAVALI 18
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
The newly added activity showitemActivity.java must be declared in AndroidManifest.xml to
make it visible to Android and hence to start it. After we run the application, We see the output as
Fig: In portrait mode, only the UI of the first fragment, Listview, is displayed (left), and the item selected
from the Listview is displayed via another activity (right).
When the device is switched to landscape mode, the UI of both the fragments, Listview and
Textview, is visible side-by-side, as
Fig: In Landscape mode, the Ul of both fragments, Listview and Textview, is displayed (left), and the item
selected from the Listview is displayed via the Textview of the second fragment (right).
Creating Fragments with Java Code
We have been defining fragments statically by using < fragment > elements in the layout file of the
application. Now learn how to add fragments to the activity during runtime. For creating, adding, and
replacing fragments to an activity dynamically, we use the FragmentManager.
FragmentManager
The FragmentManager is used to manage fragments in an activity. To access the
FragmentManager, the method used is getFragmentManager() , as shown here:
FragmentManager fragmentManager = getFragmentManager();
VISVODAYA ENGINEERING COLLEGE, KAVALI 19
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
To perform fragment transactions, we use the instance of the FragmentTransaction as shown here:
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
A new FragmentTransaction is created using the beginTransaction() method of the
FragmentManager. The following code shows how to add a fragment:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment1Activity fragment = new Fragment1Activity();
fragmentTransaction.add(R.id.fragment_container, fragment, "TAG1");
fragmentTransaction.commit();
Here the Fragment1Activity is the Java class of the fragment, which is also used to load the UI of
the fragment from its XML file. We assume that the fragment_container is the ID of the container that
exists in the layout file where we want to put our fragment. The TAG1 refers to the unique ID to identify
and access the fragment. The commit () method is used to apply the changes.
Before we add a fragment, it is a wise idea to check whether it already exists by modifying the
code as shown here:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if(null==fragmentManager.findFragmentByTag(TAGl)){
Fragment1Activity fragment = new FragmentiActivity();
fragmentTransaction.add(R.id.fragment_container, fragment, "TAG1");
}
fragmentTransaction.commit();
We can see that the findFragmentByTag () method of the FragmentManager checks to see whether
any fragment with the given tag exists.
To replace the fragment or content being displayed in the fragment_container with the View from
another fragment, we use the replace() method of the FragmentTransaction as shown here:
fragmentTransact.replace(R.id.fragment_container,fragment2, "TAG2");
In this statement, the views of fragment2 replace the content being displayed in the
fragment_container of the Activity layout. The following code identifies the fragment via the
findFragmentByid () method and then removes it:
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = fragmentManager.findFragmentByldfR.id.fragment);
fragmentTransaction.remove(fragment);
fragmentTransaction.commit() ;
Here we assume that a fragment with the ID fragment exists in the Activity. To identify the
fragment through the findFragmentByTag() method, the statement can be replaced by the following:
Fragment fragment = fragmentManager.findFragmentByTag(TAG1);
Communicating Between Fragments
We can also pass information among the fragments. The two methods provided by the Fragment
class to enable communication between fragments are setArguments() and getArguments(). The
setArguments() method stores a Bundle in the fragment, whereas the getArgumentsO method retrieves
the Bundle to fetch the passed information.
VISVODAYA ENGINEERING COLLEGE, KAVALI 20
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
The following code passes information from fragment1 to fragment 2.We assume that fragment is
the ID of the fragment container that exists in the layout file where we want to display fragment 2.
final Fragment2Activity frag2 = new Fragment2Activity();
final Bundle args = new Bundle();
String selectedItem="Text to send to fragment 2";
if(null==fragmentManager.findFragmentByTag(FRAG2)){
args.putString("item",selectedItem);
frag2.setArguments(args);
fragmentTransaction.replace(R.id.fragment,frag2);
String tag=null;
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.commit();
}
Navigating to Previous Fragments
The Activity stack keeps track of previous Activities. When we press the back button, the
Activities in the Activity stack pop up, making their views visible. In other words, the Activity stack
enables us to navigate back to previous screens by using the back button.
The same concept is applicable to fragments as well. To add the FragmentTransaction to the back
stack, we need to call the addToBackStack() method of FragmentTransaction before calling the
commit() method.
In the code shown previously, fragment 2 replaces fragment1, which was being displayed in the
fragment container of the layout file, fragment 1 is added to the back stack, making its views invisible.
Pressing the back button then reverses the previous FragmentTransaction and returns the View of the
earlier fragment, fragment1.
Retrieving Content Passed Through Bundle
We can access the content passed to the fragment via the Bundle that was saved through the
setArguments () method. The getArguments () method accesses the Bundle that may be passed to the
fragment. The following code accesses the Bundle object passed to the fragment. It also accesses the
content passed under the item key and assigns it to the String selectedltem:
String selectedltem="";
@override
public void onCreate (Bundle state) {
super.onCreate(state);
if (null == state)
state = getArguments();
if (null != state)
selectedltem = state.getstring("item");
}
Saving and Restoring the State of Fragments
Fragments can also save their state to be restored later, just like Activities. The callback methods
meant for this purpose are onSaveInstanceState () and onRestorelnstanceState().
The onSaveInstanceState() Callback: The onSaveInstanceState () callback is used for saving the status
of the fragment into a Bundle object, which is then used while restoring the fragment.
VISVODAYA ENGINEERING COLLEGE, KAVALI 21
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
@Override
public void onSaveInstanceState(Bundle savedlnstanceState) {
super.onSaveInstanceState(savedlnstanceState);
savedlnstanceState.putString("selectedfruit", selectedltem);
The onRestorelnstanceState () Callback: The onRestorelnstanceState () callback is for restoring the
fragment to its earlier saved state.
@Override
public void onRestorelnstanceState(Bundle savedlnstanceState){
super.onRestorelnstanceState(savedlnstanceState);
selectedltem = savedlnstanceState.getString()”selectedfruit");
}
To understand how fragments are created programmatically, we create an application similar to
our FragmentsApp application showing a Listview and Textview in landscape mode and only a Listview
in portrait mode.
Let's create a new Android project called FragmentCodeApp. The code in fragment1.xml is the
same as above Listing. Similarly, the code written into fragment2.xml is the same as that shown in
Listing. Write the code shown in the main layout file of the application,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height ="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:id="@+id/fragmentl"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height = "match_parent" />
<LinearLayout
android:id="@+id/fragment2"
android:layout_weight=" 0"
android:layout_width="wrap_content"
android:layout_height = "match_parent" />
</LinearLayout>
We can see that two LinearLayout elements are added to the layout file instead of the fragments.
This is because we are adding fragments dynamically through code. To load the Views defined in
fragment2.xml, the code that is written into Fragment2Activity, java is the same as that shown in Listing.
To load the views defined in fragment1.xml, write the code shown in the Java class file
FragmentlActivity. java.
com.androidunleashed.fragmentcodeapp;
import android.view.View;
import android.view.LayoutInflater;
import android.app.Fragment;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.content.Context;
import android.widget.AdapterView;
VISVODAYA ENGINEERING COLLEGE, KAVALI 22
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.content.Intent;
import android.app.FragmentManager;
public class FragmentlActivity extends Fragment{
protected static final String FRAG2 = "2";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedlnstanceState) {
Context c = getActivity().getApplicationContext() ;
View vw = inflater.inflate(R.layout.fragment1, container, false);
final String[] fruits={"Apple", "Mango", "Orange", "Grapes", "Banana"};
ListView fruitsList = (ListView) vw.findViewById(R.id.fruits_li.st);
ArrayAdapter<String> arrayAdpt= new ArrayAdapter<String>(c,
android.R.layout.simple_list_item_l, fruits);
fruitsList.setAdapter(arrayAdpt);
final FragmentManager fragmentManager = getFragmentManager();
fruitsList.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,long id){
if(null!=fragmentManager.findFragmentByTag(FRAG2)){
TextView selectedopt = (TextView) getActivity().findViewById(R.id.selectedopt);
selectedopt.setText("You have selected "+((TextView) v) .getText().toString() );
} else {
Intent intent = new Intent(getActivity().getApplicationContext(),
ShowItemActivity.class);
intent.putExtra("item",((TextView) v).getText().toString());
startActivity(intent);
}
}
});
return vw;
}
}
Creating Special Fragments
After understanding the procedure to create simple fragments, we learn to create specialized
fragments such as list fragments, dialog fragments, and preference fragments. To create these, we extend
from the following subclasses of the Fragment base class:
ListFragment
DialogFragment
PreferenceFragment
Creating a ListFragment
A ListFragment is a fragment that contains a built-in Listview that can be set to display items from
a specified data source. The data source can be an array or a cursor. To understand ListFragments, let's
create an application consisting of a Listview and a Textview. The item selected from the Listview in the
ListFragment is displayed through the Textview in the simple fragment. Let's name the new Android
project ListFragApp. We first create a fragment to hold the Textview control. So, let's add an XML file
called fragment2.xml to the res/ layout folder of our project.
VISVODAYA ENGINEERING COLLEGE, KAVALI 23
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:1ayout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Please select a fruit" />
</LinearLayout>
To load the UI of the fragment from f ragment2.xml, we need to create a Java class file. So, add a
Java class file called Fragment2Activity, java under the com.androidunleashed.listfragapp package.
package com.androidunleashed.listfragapp;
import android.app.Fragment;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.View;
import android.view.LayoutInflater;
public class Fragment2Activity extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
}
}
We can directly add a Java class file that extends the ListFragment class. In this Java class file, we
write code to define the items to be displayed through the Listview of the ListFragment and also to
display the item selected from the Listview through the Textview of the Fragment 2. So, add a Java class
called Fragment1Activity. java to the project and write the code as
package com.androidunleashed.1istfragapp;
import android.app.ListFragment;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
public class Fragment1Activity extends ListFragment {
final String[] fruits=("Apple", "Mango", "Orange", "Grapes", "Banana"};
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
ArrayAdapter<String> arrayAdpt = new ArrayAdapter<String>(getActivity(),
android.R. layout. simple_list_itern_l, fruits) ;
setListAdapter(arrayAdpt);
}
@Override
public void onListltemClick(ListView 1, View v, int position, long id) {
TextView selectedOpt = (TextView) getActivity().findViewById(R. id.selectedopt);
selectedOpt.setText("You have selected "+((Textview) v).getText().toString());
}
}
We display the name of the selected fruit through the Textview control that we defined in
fragment2 .xml. To accommodate both the fragments, code is written into activity,_list_frag_app.xml as
VISVODAYA ENGINEERING COLLEGE, KAVALI 24
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:1ayout_width=" match_parent"
android:1ayout_height="match_parent"
android:orientation="horizontal" >
<fragment
android:name="com.androidunleashed.listfragapp.FragmentlActivity"
android:id="@+id/fragment1"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<fragment
android:name="com.androidunleashed.listfragapp.Fragment2Activity"
android:id="@+id/fragment2"
android:layout_weight="0"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
We don't have to write any code into the Java activity file of the application
ListFragAppActivity.java. The default code in the activity file unchanged, as
com.androidunleashed.listfragapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class ListFragAppActivity extends Activity {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_list_frag_app);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_list_frag_app, menu);
return true;
}
}
After running the application, we see the two fragments side-by-side, as
Fig: The Listview displayed via ListFragment (left), and the Item selected from the Listview of ListFragment, displayed via
the Textview of the second fragment (right)
VISVODAYA ENGINEERING COLLEGE, KAVALI 25
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Using a DialogFragment
We can display a DialogFragment by extending the DialogFragment base class, which in turn is
derived from the Fragment class. To demonstrate DialogFragment, let's create a new Android project
called DialogFragApp. In this project, we use two fragments. One is used to show a DialogFragment,
and the other displays a Textview The selected button in the DialogFragment is displayed via the
Textview control in the second fragment.
Define the UI of the simple fragment that consists of a Textview. Write the code shown in Listing
into the fragment2.xml file.
<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/selectedopt"
android:layout_width="match_parent"
android:layout_height = "wrap_content"
android:text="Select Open Dialog Button" />
</LinearLayout>
To load the UI of the fragment from fragment2 .xml, a Java class file called
Fragment2Activity.java is added to the project.
import android.app.Fragment;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.View;
import android.view.LayoutInflater;
public class Fragment2Activity extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
}
}
To accommodate the fragment defined in fragments.xml, we need to write code into the layout file
activity_dialog_frag_app.xml, as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width= "match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<fragment
android:name="com.androidunleashed.dialogfragapp.Fragment2Activity"
android:id="@+id/fragment2"
android:layout_weight="0"
android:layout_width= "wrap_content"
android:layout_height="match_parent" />
<Button
android:id="@+id/dialog_button"
android:layout_width="match_parent"
VISVODAYA ENGINEERING COLLEGE, KAVALI 26
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
android:layout_height= "wrap_content"
android:text= "Open Dialog" />
</LinearLayout>
Both the Fragment and Button controls are nested inside the LinearLayout container. To display a
DialogFragment, write the code into the Fragment1Activity.Java file
import android.app.DialogFragment;
import android.app.Fragment;
import android.os.Bundle;
import android.app.Dialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
public class Fragment1Activity extends DialogFragment{
static Fragment1Activity newInstance(String title) {
Fragment1Activity fragment = new Fragment1Activity();
Bundle args = new Bundle () ;
args.putString("title", title);
fragment.setArguments(args);
return fragment;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString("title") ;
Dialog diag = new
AlertDialog.Builder(getActivity()).setIcon(R.drawable.ic_launcher).setTitle(title).setPosi
tiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((MainActivity)getActivity()).PositiveButton();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((MainActivity) getActivity()).NegativeButton();
}
}).create();
return diag;
}
}
When OK is selected, the positiveButtonO method from the activity is called. Similarly, when
Cancel is selected, the NegativeButton () method from the activity is called. The method returns the
created AlertDialog. In the Java activity file, we need to write code to invoke the DialogFragment. The
code must be written to take the necessary action when OK or cancel is selected from the
DialogFragment. The Code written into the Java activity file DialogFragAppActivity. java is
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.widget.TextView;
public class DialogFragAppActivity extends Activity {
@Override
VISVODAYA ENGINEERING COLLEGE, KAVALI 27
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog_frag_app);
Button dialogButton = (Button) findViewById(R.id.dialog_button);
dialogButton.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View argO) {
Fragment1Activity dialogFragment =
Fragment1Activity.newInstance("Continue Processing?");
dialogFragment.show(getFragmentManager(), "Dialog Fragment Example");
}
});
}
public void PositiveButton() {
TextView selectedopt = (TextView) findViewById(R.id.selectedopt);
selectedopt.setText("You have selected OK button");
}
public void NegativeButton() {
TextView selectedopt = (TextView) findViewById(R.id.selectedopt);
selectedopt.setText("You have selected Cancel button");
}
}
The
Fig: Textview and Button displayed on application startup (left), the DialogFragment appears after clicking the button
(middle), and the Textview showing that the DialogFragment OK button was clicked (right)
After we click the open Dialog button again, the DialogFragment opens up once more. This time,
if we select Cancel from the DialogFragment, the Textview displays the message You have selected
Cancel button, as
Fig: The Textview showing that the DialogFragment Cancel button was clicked
VISVODAYA ENGINEERING COLLEGE, KAVALI 28
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Using PreferenceFragment
PreferenceFragment is a fragment that enables users to configure and personalize an application.
The PreferenceFragment can contain several Preference Views that help in uniformly setting application.
Preference View Description
PreferenceScreen The root element of the XML used to define a preference screen
checkBoxPreference Displays a simple check box that returns true when checked otherwise
returns false
ListPreference Displays a list of radio buttons allowing the user to select one
EditText Preference Displays a dialog with an EditText control allowing the user to enter text
RingtonePreference Displays radio buttons indicating the ringtones available for selection
PreferenceCategory Used in grouping related preferences in categories
Preference A custom preference that acts like a Button control
To understand how application preferences are set, let's create a new Android project called
PreferenceFragApp. We add an XML file called preferences.xml. This file contains the preference views
we want to display to the user to configure the application.
The code written into the preferences. xml file is
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="Category 1">
<CheckBoxPreference
android:title="Pizza"
android:defaultValue="false"
android:key="Pizzakey" />
<EditTextPreference android:key="Namekey"
android:title="Enter your name: "
android:dialogTitle="Enter your information">
</EditTextPreference>
</PreferenceCategory>
<PreferenceCategory android:title="Category 2">
<RingtonePreference android:showDefault="true"
android:key="Audio"
android:title="Select sound"
android:ringtoneType="notification">
</RingtonePreference>
<ListPreference android:title="Fruits List "
android:key="fruits_list"
android:entries="@array/fruits"
android:entryValues="@array/fruitselected"
android:dialogTitle="Choose a fruit">
</ListPreference>
</PreferenceCategory>
<Preference
android:title="Submit"
android:key="submitPref"/>
</PreferenceScreen>
VISVODAYA ENGINEERING COLLEGE, KAVALI 29
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
We can see that the Preference views are shown in two categories: Category 1 and Category 2.
Next, we need to define two arrays in the strings.xml resource file: one to display text for the radio
button in the ListPreference and the second to store the values of the corresponding elements in the first
array. After we define the two arrays, the strings.xml file appears as
<resources>
<string name="app_name">PreferenceFragApp</string>
<string-array name="fruits">
<item>Apple</item>
<item>Mango</item>
<item>Orange</item>
<item>Grapes</item>
<item>Banana</item>
</string-array>
<string-array name="fruitselected">
<item>You have selected Apple</item>
<item>You have selected Mango</item>
<item>You have selected Orange</item>
<item>You have selected Grapes</item>
<item>You have selected Banana</item>
</string-array>
</resources>
To load the Preference views defined in preferences.xml, a Java class file called prefActivity. java
is added to the project. Write the code in Java class file PrefActivity.java as
import android.app.Activity;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceFragment;
public class PrefActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,new
PrefsFragment()).commit();
}
public static class PrefsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
addPreferencesFromResource(R.xml.preferences);
Preference submitpref = (Preference) findPreference("submitPref");
submitpref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
getActivity().finish();
return true;
}
});
}
}
}
VISVODAYA ENGINEERING COLLEGE, KAVALI 30
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
To display the options selected from the Preference views shown in the PreferenceFragment, we
need to define four Textview controls in the layout file activity_preference_frag.xml.
<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:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/pizza"/>
<TextView
android:layout_width= "match_parent"
android:layout_height="wrap_content"
android:id="@+id/name"/>
<TextView
android:layout_width= "match_parent"
android:layout_height="wrap_content"
android:id="@+id/ringtone"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/fruit"/>
</LinearLayout>
To display the PreferenceFragment and show the preferences selected by the user, we need to write
the code into the main activity file PreferenceFragAppActivity.java.
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.preference.PreferenceManager;
import android.content.SharedPreferences;
import android.widget.TextView;
public class PreferenceFragAppActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startActivity(new Intent(this,PrefActivity.class));
}
@Override
public void onResume() {
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
TextView Pizza = (TextView) findViewById(R.id.pizza);
TextView Name = (TextView) findViewById(R.id.name);
TextView Ringtone = (TextView) findViewById(R.id.ringtone);
TextView Fruit = (TextView) findViewById(R.id.fruit);
if(Boolean.valueOf(prefs.getBoolean("Pizzakey",false)))
Pizza.setText("You have selected Pizza");
else
Pizza.setText("");
Ringtone.setText("The ringtone selected is " + prefs.getString("Audio","Silent"));
Name.setText("The name entered is " + prefs.getString("Namekey",""));
String selectedFruit = prefs.getString("fruits_list", "Apple");
VISVODAYA ENGINEERING COLLEGE, KAVALI 31
III.BTECH II-SEM, CSE: MOBILE APPLICATION DEVELOPMENT (21A050422)
Fruit.setText(selectedFruit);
}
}
Fig: A PreferenceFragment showing different Preference Views (left), the EditTextPreference prompting for information
(middle), and the RingtonePreference prompting to select a ringtone type (right)
Finally, we click the submit button at the bottom of the PreferenceFragment to close the fragment
and display the selected preferences. All the selected preferences are shown through the Textview
controls.
Fig; The ListPreference showing selectable fruits in the form of radio buttons (left) and all the selected preferences
displayed via Textview controls (right)
VISVODAYA ENGINEERING COLLEGE, KAVALI 32