Professional Documents
Culture Documents
ICT (Competency 3) - Object-Oriented Programming Training Manual (Android)
ICT (Competency 3) - Object-Oriented Programming Training Manual (Android)
COMPUTER PROGRAMMING NC IV
Training Manual
Core CompetenCy 3 (Android)
V9 FS ION 2016
Fasttrack IT Academy
G/F King’s Court II Bldg., Chino Roces Ave.
cor. Dela Rosa St., Makati City
Tel: (02s 759-4-FIT (348)
Mob ile: 0917-8383-FIT (348a
Email: inquirypfitacademy.ph
Object-Oriented Programming (Android) – Core Competency 3
Course Syllabus
Laboratory
Topic Week Session Hours Slides
1
Laboratory
Topic Week Session Hours Slides
Switch
ProgressBar 9-11 10 4 J
Laboratory Exercise 10
AlertDialog
Applying Custom Styles to Widgets 12-13 11 4 K
Laboratory Exercise 11
ListView and Simple Adapters
14-15 12 4 L
Laboratory Exercise 12
Custom ListView and Adapter
14-15 13 4 M
Laboratory Exercise 13
Case Study: Meal Order App 16-18 14 4 ---
Case Study: Meal Order App (cont…) 16-18 15 4 ---
2
TABLE OF CONTENTS
3
EVENT HANDLERS AND LISTENERS.............................................................................................................................................................. 81
LABORATORY EXERCISE 5..........................................................................................................................................87
LINEAR LAYOUT............................................................................................................................................................................................ 92
RELATIVE LAYOUT........................................................................................................................................................................................ 95
TABLE LAYOUT............................................................................................................................................................................................. 98
LABORATORY EXERCISE 6........................................................................................................................................100
RADIO BUTTONS....................................................................................................................................................................................... 104
CHECKBOX................................................................................................................................................................................................. 108
LABORATORY EXERCISE 7........................................................................................................................................113
IMAGEVIEW............................................................................................................................................................................................... 118
SPINNER..................................................................................................................................................................................................... 123
LABORATORY EXERCISE 8........................................................................................................................................126
SEEKBAR.................................................................................................................................................................................................... 130
TOGGLE BUTTON....................................................................................................................................................................................... 132
LABORATORY EXERCISE 9........................................................................................................................................136
SWITCH...................................................................................................................................................................................................... 143
PROGRESSBAR........................................................................................................................................................................................... 144
LABORATORY EXERCISE 10......................................................................................................................................148
ALERTDIALOG............................................................................................................................................................................................ 154
APPLYING CUSTOM STYLES TO WIDGETS................................................................................................................................................ 159
LABORATORY EXERCISE 11......................................................................................................................................164
LISTVIEW AND SIMPLE ADAPTERS........................................................................................................................................................... 172
LABORATORY EXERCISE 12......................................................................................................................................176
CUSTOM ADAPTERS.................................................................................................................................................................................. 177
LABORATORY EXERCISE 13......................................................................................................................................183
CASE STUDY: MEAL ODER APP................................................................................................................................................................ 192
4
Chapter 1
Android SDK and Development Environment
Objectives:
At the end of this chapter the student should be able to:
Understand and Learn what is Android and its concepts.
Know Android Version and Features
Understand Android architecture and its History
Obtain the tools and SDK for developing Android
Use Emulator to test and run mobile applications.
Android offers a unified approach to application development for mobile devices which means developers
need only develop for Android, and their applications should be able to run on different devices powered by
Android. The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007
whereas the first commercial version, Android 1.0, was released in September 2008.
On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly
Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of
functionality and performance. The source code for Android is available under free and open source software
licenses. Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel
changes, under the GNU General Public License version 2.
5
Versions and Features of Android
Like any software, Android is improved over time, which is reflected in its version numbers. However, the
relationship between different version numbers can be confusing, the table on the below shows the different
versions of Android.
6
The code names of android ranges from A to L currently, such as Aestro, Blender, Cupcake, Donut, Eclair,
Froyo, Gingerbread, Honeycomb, Ice Cream Sandwich, Jelly Bean, KitKat and Lollipop. Let's understand the
android history in a sequence.
The Android version number itself partly tells the story of the software platform’s major and minor
releases. What is most important is the API level. Version numbers change all the time, sometimes because the
APIs have changed, and other times because of minor bug fixes or performance improvements.
Features of Android
Android is a powerful operating system competing with Apple 4GS and supports great features. Few of
them are listed below:
Feature Description
Beautiful UI Android OS basic screen provides a beautiful and intuitive user interface.
Connectivity GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and
WiMAX.
Storage SQLite, a lightweight relational database, is used for data storage purposes.
Media support H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3,
MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP
Messaging SMS and MMS
Web browser Based on the open-source WebKit layout engine, coupled with Chrome's V8
JavaScript engine supporting HTML5 and CSS3.
Multi-touch Android has native support for multi-touch which was initially made available in
handsets such as the HTC Hero.
7
Multi-tasking User can jump from one task to another and same time various application can
run simultaneously.
Resizable widgets Widgets are resizable, so users can expand them to show more content or
shrink them to save space
Multi-Language Supports single direction and bi-directional text.
GCM Google Cloud Messaging (GCM) is a service that lets developers send short
message data to their users on Android devices, without needing a proprietary
sync solution.
Wi-Fi Direct A technology that lets apps discover and pair directly, over a high-bandwidth
peer-to-peer connection.
Android Beam A popular NFC-based technology that lets users instantly share, just by
touching two NFC-enabled phones together.
Android Applications
Android applications are usually developed in the Java language using the Android Software Development
Kit. Once developed, Android applications can be packaged easily and sold out either through a store such
as Google Play,SlideME,Opera Mobile Store,Mobango,F-droid and the Amazon Appstore.
Android powers hundreds of millions of mobile devices in more than 190 countries around the world. It's
the largest installed base of any mobile platform and growing fast. Every day more than 1 million new Android
devices are activated worldwide.
Categories of Application
There are many android applications in the market. The top categories are:
8
Android Devices in the Market
August 2008, Google announced Android Market, an online application store for Android devices, and
made it available to users in October 2008. Using the Market application that is preinstalled on their Android
device, users can simply download third-party applications directly onto their devices. Both paid and free
applications are supported on the Android Market, though paid applications are available only to users in certain
countries due to legal issues.
Similarly, in some countries, users can buy paid applications from the Android Market, but developers
cannot sell in that country. As an example, at the time of writing, users in India can buy apps from the Android
Market, but developers in India cannot sell apps on the Android Market. The reverse may also be true; for
example, users in South Korea cannot buy apps, but developers in South Korea can sell apps on the Android
Market.
Android Architecture
Android operating system is a stack of software components which is roughly divided into five sections
and four main layers as shown below in the architecture diagram.
9
Linux kernel
At the bottom of the layers is Linux - Linux 3.6 with approximately 115 patches. This provides a level of
abstraction between the device hardware and it contains all the essential hardware drivers like camera, keypad,
display etc. Also, the kernel handles all the things that Linux is really good at such as networking and a vast array
of device drivers, which take the pain out of interfacing to peripheral hardware.
Libraries
On top of Linux kernel there is a set of libraries including open-source Web browser engine WebKit, well
known library libc, SQLite database which is a useful repository for storage and sharing of application data,
libraries to play and record audio and video, SSL libraries responsible for Internet security etc.
Android Libraries
This category encompasses those Java-based libraries that are specific to Android development.
Examples of libraries in this category include the application framework libraries in addition to those that facilitate
user interface building, graphics drawing and database access. A summary of some key core Android libraries
available to the Android developer is as follows:
android.app − Provides access to the application model and is the cornerstone of all Android
applications.
android.content − Facilitates content access, publishing and messaging between applications and
application components.
android.database − Used to access data published by content providers and includes SQLite
database management classes.
android.opengl − A Java interface to the OpenGL ES 3D graphics rendering API.
android.os − Provides applications with access to standard operating system services including
messages, system services and inter-process communication.
android.text − Used to render and manipulate text on a device display.
android.view − The fundamental building blocks of application user interfaces.
android.widget − A rich collection of pre-built user interface components such as buttons, labels, list
views, layout managers, radio buttons etc.
android.webkit − A set of classes intended to allow web-browsing capabilities to be built into
applications.
Having covered the Java-based core libraries in the Android runtime, it is now time to turn our attention to
the C/C++ based libraries contained in this layer of the Android software stack.
10
Android Runtime
This is the third section of the architecture and available on the second layer from the bottom. This section
provides a key component called Dalvik Virtual Machine which is a kind of Java Virtual Machine specially designed
and optimized for Android.
The Dalvik VM makes use of Linux core features like memory management and multi-threading, which is
intrinsic in the Java language. The Dalvik VM enables every Android application to run in its own process, with its
own instance of the Dalvik virtual machine. The Android runtime also provides a set of core libraries which enable
Android application developers to write Android applications using standard Java programming language.
Application Framework
The Application Framework layer provides many higher-level services to applications in the form of Java
classes. Application developers are allowed to make use of these services in their applications.
Applications
You will find all the Android application at the top layer. You will write your application to be installed on this
layer only. Examples of such applications are Contacts Books, Browser, Games etc.
11
Second point is that all the required tools to develop Android applications are freely available and can be
downloaded from the Web. Following is the list of software's you will need before you start your Android
application programming.
Here last two components are optional and if you are working on Windows machine then these
components make your life easy while doing Java based application development. So let us have a look how to
proceed to set required environment.
You can download the latest version of Java JDK from Oracle's Java site:
http://www.oracle.com/technetwork/java/javase/downloads/index.html.
You will find instructions for installing JDK in downloaded files, follow the given instructions to install and
configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that
contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and installed the JDK in C:\jdk1.6.0_15, you would have to put the following
line in your C:\autoexec.bat file.
Alternatively, you could also right-click on My Computer, select Properties, thenAdvanced, then
Environment Variables. Then, you would update the PATH value and press the OK button.
On Linux, if the SDK is installed in /usr/local/jdk1.6.0_15 and you use the C shell, you would put the
following code into your .cshrc file.
12
Alternatively, if you use an Integrated Development Environment (IDE) Eclipse, then it will know
automatically where you have installed your Java.
Second point is that all the required tools to develop Android applications are open source and can be
downloaded from the Web. Following is the list of software's you will need before you start your Android
application programming.
13
Java JDK5 or later version
Java Runtime Environment (JRE) 6
Android Studio
Installation
So let's launch Android Studio.exe, Make sure before launch Android Studio, Our Machine should require
installed Java JDK. To install Java JDK, take a references of Android environment setup.
14
Once you launched Android Studio, it’s time to mention JDK5 path or later version in android studio installer.
15
Need to check the components, which are required to create applications, below the image has
selected Android Studio,Android SDK,Android Virtual Machine and performance(Intel chip).
Need to specify the location of local machine path for Android studio and Android SDK, below the image
has taken default location of windows 8.1 x64 bit architecture.
16
Need to specify the ram space for Android emulator by default it would take 512MB of local machine RAM.
At final stage, it would extract SDK packages into our local machine, it would take a while time to finish the
task and would take 2626MB of Hard disk space.
17
After done all above steps perfectly, you must get finish button and it will be open android studio project
with Welcome to android studio message as shown below.
You can start your application development by calling start a new android studio project. in a new
installation frame should ask Application name, package information and location of the project.
18
After entered application name, it going to be called select the form factors your application runs on, here
need to specify Minimum SDK, in our tutorial, I have declared as API21: Android 5.0(Lollipop)
The next level of installation should contain selecting the activity to mobile, it specifies the default layout for
Applications
19
At the final stage it going to be open development tool to write the application code.
1 – The project directory hierarchy. Here you can view the source code, layout files, binaries, app figures
and further configuration files. From this section you can also quickly add new files to the project.
2 – Everything (or almost everything) you will need to configure your graphical interfaces. Text boxes,
images, buttons, progress bars, and other widgets. To insert a widget in the layout just drag it and
carefully drop it on the preview device screen.
3 – You can choose between developing the graphical interface based on drag and drop or pure code.
Preferences vary from person to person. I particularly like to use the best of each. Drag and drop to add
the widget and pure code to fine-tune.
4 – A preview of your app screen appears here. It’s always good to get feedback to see if everything is in
the right place.
5 – In theory, you can select a widget and configure all its properties from these fields. In practice, it is
almost always preferable to use code for this.
6 – Many files can be opened at the same time and you will see them here. XML files for the design of
graphical interface, settings, features and .java for programming the core of the app.
20
Step 3 - Create Android Virtual Device
To test your Android applications, you will need a virtual Android device. So before we start writing our
code, let us create an Android virtual device. Launch Android AVD Manager Clicking AVD_Manager icon as
shown below
After Click on a virtual device icon, it going to be shown by default virtual devices which are present on
your SDK, or else need to create a virtual device by clicking Create new Virtual device button
If your AVD is created successfully it means your environment is ready for Android application
development. If you like, you can close this window using top-right cross button. Better you re-start your machine
and once you are done with this last step, you are ready to proceed for your first Android example but before that
we will see few more important concepts related to Android Application Development.
21
Hello Word Example
Before Writing a Hello word code, you must know about XML tags. To write hello word code, you should
redirect to App>res>layout>Activity_main.xml
To show hello word, we need to call text view with layout (about text view and layout, you must take
references at Relative Layout and Text View).
Need to run the program by clicking Run>Run App or else need to call
shift+f10 key. Finally, result should be placed at Virtual devices as shown below
22
Test and Run Android Projects
When building a mobile application, it's important that you always test your application on a real device
before releasing it to users. This page describes how to set up your development environment and Android-
powered device for testing and debugging on the device.
You can use any Android-powered device as an environment for running, debugging, and testing your
applications. The tools included in the SDK make it easy to install and run your application on the device each time
you compile. You can install your application on the device directly from Android Studio or from the command line
with ADB. If you don't yet have a device, check with the service providers in your area to determine which Android-
powered devices are available.
Note: When developing on a device, keep in mind that you should still use the Android emulator to test your
application on configurations that are not equivalent to those of your real device. Although the emulator does not
allow you to test every device feature (such as the accelerometer), it does allow you to verify that your application
functions properly on different versions of the Android platform, in different screen sizes and orientations, and
more.
Android-powered devices have a host of developer options that you can access on the phone, which let
you:
Enable debugging over USB.
Quickly capture bug reports onto the device.
Show CPU usage on screen.
23
Draw debugging information on screen such as layout bounds, updates on GPU views and hardware
layers, and other information.
Plus, many more options to simulate app stresses or enable debugging options.
To access these settings, open the Developer options in the system Settings. On Android 4.2 and higher,
the Developer options screen is hidden by default. To make it visible, go to Settings > About phone and tap Build
number seven times. Return to the previous screen to find Developer options at the bottom.
24
c. If you're developing on Ubuntu Linux, you need to add a udev rules file that contains a USB
configuration for each type of device you want to use for development. In the rules file, each
device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor}
property. For a list of vendor IDs, see USB Vendor IDs, below. To set up device detection on
Ubuntu Linux:
> Log in as root and create this file: /etc/udev/rules.d/51-android.rules.
Use this format to add each vendor to the file:
SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"
In this example, the vendor ID is for HTC. The MODE assignment specifies
read/write permissions, and GROUPdefines which Unix group owns the device node.
Note: The rule syntax may vary slightly depending on your environment. Consult the
udev documentation for your system as needed. For an overview of rule syntax, see this
guide to writing udev rules.
> Now execute:
chmod a+r /etc/udev/rules.d/51-android.rules
Note: When you connect a device running Android 4.2.2 or higher to your computer, the system shows a dialog
asking whether to accept an RSA key that allows debugging through this computer. This security mechanism
protects user devices because it ensures that USB debugging and other ADB commands cannot be executed
unless you're able to unlock the device and acknowledge the dialog. This requires that you have ADB version
1.0.31 (available with SDK Platform-tools r16.0.1 and higher) in order to debug on a device running Android 4.2.2
or higher.
When plugged in over USB, you can verify that your device is connected by executing ADB devices from
your SDK platform-tools/ directory. If connected, you'll see the device name listed as a "device." If using Android
Studio, run or debug your application as usual. You will be presented with a Device Chooser dialog that lists the
available emulator(s) and connected device(s). Select the device upon which you want to install and run the
application. If using the Android Debug Bridge (ADB), you can issue commands with the -d flag to target your
connected device.
25
Laboratory Exercise 1
Problem Statement
Create a new project using Android Studio and display your full name at the center of your design output.
Use emulator to run and test your app. Once done call your teacher to check your work.
Requirements:
Composed of only one Activity which is the MainActivity.
Use Bluestacks emulator to run and test your app.
Follow the design layout given below.
Legend:
A – This is the layout design for the Main Activity that labeled with your full name at the center. Use
emulator to test your app.
26
Solution
1. In Android Studio, create a new project.
27
3. For Minimum SDK, select API 18(Jelly Bean Android 4.3)
4. Leave all of the other options (TV, Wear, and Glass) unchecked and click Next.
28
5. Under Add an activity to <template>, select Empty Activity and click Next.
7. Your Android project is now a basic "Hello World" app that contains some default files. Try to run your app.
29
A. XML Activity Layout Design Code
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
30
Chapter 2
Fundamental Structure of Android
Objectives:
At the end of this chapter the student should be able to:
Understand the Android Project Anatomy and Activity Life Cycle.
Learn how to use Raw and Drawable files and Identify different intents.
Apply sounds & animation effects and create Splash Screen
31
AndroidManifest.xml — The manifest file glues everything together. It is this file that explains what the
application consists of, what all its main building blocks are, what permissions it requires, and so on
(We will see the complete AndroidManifest.xml file later in the chapter).
If you have worked with C, C++ or Java programming language then you must have seen that your
program starts from main() function. Very similar way, Android system initiates its program with in an Activity
starting with a call on onCreate() callback method. There is a sequence of callback methods that start up an
activity and a sequence of callback methods that tear down an activity as shown in the below Activity life cycle
diagram: (image courtesy : android.com )
32
The Activity class defines the following call backs i.e. events. You don't need to implement all the
callbacks methods. However, it's important that you understand each one and implement those that ensure your
app behaves the way users expect.
Callback Description
onCreate() This is the first callback and called when the activity is first created.
onStart() This callback is called when the activity becomes visible to the user.
onResume() This is called when the user starts interacting with the application.
onPause() The paused activity does not receive user input and cannot execute any code
and called when the current activity is being paused and the previous activity is
being resumed.
onStop() This callback is called when the activity is no longer visible.
onDestroy() This callback is called before the activity is destroyed by the system.
onRestart() This callback is called when the activity restarts after stopping it.
This example will take you through simple steps to show Android application activity life cycle. Follow the
following steps to modify the Android application we created in Hello World Example:
Step Description
1 You will use eclipse IDE to create an Android application and name it asHelloWorld under
a package com.example.helloworld as explained in theHello World Example chapter.
2 Modify main activity file MainActivity.java as explained below. Keep rest of the files
unchanged.
3 Run the application to launch Android emulator and verify the result of the changes done
in the application.
package com.example.helloworld;
import
android.os.Bundle;
import
android.app.Activity;
import android.util.Log;
33
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(msg, "The onCreate() event");
}
An activity class loads all the UI component using the XML file available in res/layout folder of the project.
Following statement loads UI components from res/layout/activity_main.xml file:
An application can have one or more activities without any restrictions. Every activity you define for your
application must be declared in yourAndroidManifest.xml file and the main activity for your app must be declared in
the manifest with an <intent-filter> that includes the MAIN action and LAUNCHER category as follows:
34
If either the MAIN action or LAUNCHER category are not declared for one of your activities, then your app
icon will not appear in the Home screen's list of apps.
Let's try to run our modified Hello World! application we just modified. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity
files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display Emulator window and you should see following log messages.
Let us try to click Red button on the Android emulator and it will generate following events messages
in LogCat window in Android Studio IDE:
35
Raw and Drawable Files
There are many more items which you use to build a good Android application. Apart from coding for the
application, you take care of various other resources like static content that your code uses, such as bitmaps,
colors, layout definitions, user interface strings, animation instructions, and more. These resources are always
maintained separately in various sub-directories under res/ directory of the project.
This will explain you how you can organize your application resources, specify alternative resources and
access them in your applications.
36
xml/ Arbitrary XML files that can be read at runtime by callingResources.getXML().
You can save various configuration files here which will be used at run time.
Alternative Resources
Your application should provide alternative resources to support specific device configurations. For
example, you should include alternative drawable resources ( i.e.images ) for different screen resolution and
alternative string resources for different languages. At runtime, Android detects the current device configuration
and loads the appropriate resources for your application.
To specify configuration-specific alternatives for a set of resources, follow the following steps
Create a new directory in res/ named in the form <resources_name>-<config_qualifier>.
Here resources_name will be any of the resources mentioned in the above table, like layout, drawable
etc. The qualifier will specify an individual configuration for which these resources are to be used. You
can check official documentation for a complete list of qualifiers for different type of resources.
Save the respective alternative resources in this new directory. The resource files must be named
exactly the same as the default resource files as shown in the below example, but these files will have
content specific to the alternative. For example, though image file name will be same but for high
resolution screen, its resolution will be high.
Below is an example which specifies images for a default screen and alternative images for high resolution
screen.
Accessing Resources
During your application development you will need to access defined resources either in your code, or in
your layout XML files. Following section explains how to access your resources in both the scenarios.
37
Accessing Resources in Code
When your Android application is compiled, a R class gets generated, which contains resource IDs for all
the resources available in your res/ directory. You can use R class to access that resource using sub-directory and
resource name or directly resource ID. To access res/drawable/myimage.png and set an ImageView you will use
following code:
Here first line of the code make use of R.id.myimageview to get ImageView defined with id myimageview
in a Layout file. Second line of code makes use of R.drawable.myimage to get an image with name myimage
available in drawable sub-directory under /res.
Now you can set the text on a TextView object with ID msg using a resource ID as follows:
38
This application code will load this layout for an Activity, in the onCreate() method as follows
Now you can use these resources in the following layout file to set the text color and text string as follows:
Now if you will go through previous chapter once again where I have explained Hello World! example, and
I'm sure you will have better understanding on all the concepts explained in this chapter. So I highly recommend to
check previous sections for working example and check how I have used various resources at very basic level.
39
Working with Intents and Bundles
An Android Intent is an abstract description of an operation to be performed. It can be used
with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components,
and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
The intent itself, an Intent object, is a passive data structure holding an abstract description of an operation to be
performed.
For example, let's assume that you have an Activity that needs to launch an email client and sends an
email using your Android device. For this purpose, your Activity would send an ACTION_SEND along with
appropriate chooser, to the Android Intent Resolver. The specified chooser gives the proper interface for the user
to pick how to send your email data.
Above syntax is calling startActivity method to start an email activity and result should be as shown below.
For example, assume that you have an Activity that needs to open URL in a web browser on your Android
device. For this purpose, your Activity will send ACTION_WEB_SEARCH Intent to the Android Intent Resolver to
open given URL in the web browser. The Intent Resolver parses through a list of Activities and chooses the one
that would best match your Intent, in this case, the Web Browser Activity. The Intent Resolver then passes your
web page to the web browser and starts the Web Browser Activity.
40
Intent Objects
An Intent object is a bundle of information which is used by the component that receives the intent as well
as information used by the Android system. An Intent object can contain the following components based on what
it is communicating or going to perform:
Action
This is mandatory part of the Intent object and is a string naming the action to be performed
— or, in the case of broadcast intents, the action that took place and is being reported. The action
largely determines how the rest of the intent object is structured. The Intent class defines a number of
action constants corresponding to different intents. Here is a list of Android Intent Standard Actions.
The action in an Intent object can be set by the setAction() method and read by getAction().
Data
Adds a data specification to an intent filter. The specification can be just a data type (the
mimeType attribute), just a URI, or both a data type and a URI. A URI is specified by separate
attributes for each of its parts. These attributes that specify the URL format are optional, but also
mutually dependent:
o If a scheme is not specified for the intent filter, all the other URI attributes are ignored.
o If a host is not specified for the filter, the port attribute and all the path attributes are ignored.
41
8 ACTION_SYNC
It going to be synchronous the data,Constant Value
isandroid.intent.action.SYNC
9 ACTION_SYSTEM_TUTORIAL
It will start the platform-defined tutorial(Default tutorial or start up tutorial)
10 ACTION_TIMEZONE_CHANGED
It intimates when time zone has changed
11 ACTION_UNINSTALL_PACKAGE
It is used to run default uninstaller
Category
The category is an optional part of Intent object and it's a string containing additional information about the
kind of component that should handle the intent. The addCategory() method places a category in an Intent object,
removeCategory() deletes a category previously added, and getCategories() gets the set of all categories currently
in the object. Here is a list of Android Intent Standard Categories. You can check detail on Intent Filters in below
section to understand how do we use categories to choose appropriate activity corresponding to an Intent.
Extras
This will be in key-value pairs for additional information that should be delivered to the component handling
the intent. The extras can be set and read using the putExtras() and getExtras() methods respectively. Here is a list
of Android Intent Standard Extra Data
Flags
These flags are optional part of Intent object and instruct the Android system how to launch an activity, and
how to treat it after it's launched etc.
Component Name
This optional field is an android ComponentName object representing either Activity, Service or
BroadcastReceiver class. If it is set, the Intent object is delivered to an instance of the designated class otherwise
Android uses other information in the Intent object to locate a suitable target. The component name is set by
setComponent(), setClass(), or setClassName() and read by getComponent().
42
Types of Intents
There are following two types of intents supported by Android.
Explicit Intents
Explicit intent going to be connected internal world of application, suppose if you want to connect one
activity to another activity, we can do this quote by explicit intent, below image is connecting first activity to second
activity by clicking button.
These intents designate the target component by its name and they are typically used for application-
internal messages - such as an activity starting a subordinate service or launching a sister activity. For example:
43
Implicit Intents
These intents do not name a target and the field for the component name is left blank. Implicit intents are
often used to activate components in other applications. For example:
The target component which receives the intent can use the getExtras() method to get the extra data sent
by the source component. For example:
44
Laboratory Exercise 2
Problem Statement
Create an app that display three different Activity and pass String value using Intent. Using a button, this
can open/display another activity with a back button in the navigation bar. Pass your name from Main Activity to
Second Activity and display using Toast. In the Second Activity, pass you section and teacher name to the third
activity and display using a Toast. See the output below.
Requirements:
Composed of three Activity namely: MainActivity, SecondActivity, and ThirdActivity.
Use Toast for displaying Student name, Section and Teacher name.
Use button to trigger to open/display another activity.
Legend:
A – This is the layout design for the Main Activity that labeled with TextView with “1 st Activity” and one
button below. When the user taps the button the Second Activity will display.
B – This is the Second Activity when appear it automatically popup a toast with a Student name. When the
button “other activity” taps it display the Third Activity.
C – This is the Third Activity when appear it automatically display a toast message with Section and
teacher’s name.
45
Solution (Code Snippet)
A. Create a new project in Android Studio with three Activities (see the figure below the project structure of
the file. Create an empty activity for Second and Third Activity.
46
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Other Activity"
android:id="@+id/button2"
android:layout_marginTop="63dp"
android:layout_below="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />
</RelativeLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open Activity"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="79dp" />
</RelativeLayout>
47
Java File: SecondActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast;
public class SecondActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second);
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import android.view.View; import android.widget.Button;
public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
48
D. Android Manifest File
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
49
Splash Screen
Cold starting an application on an Android device usually takes a couple of seconds. During this time,
users need feedback to let them know your application is loading. Here is one way to create a splash screen for
your application.
For the sound/music, under res folder you should create raw folder. To do that right click on the res folder
> new > directory.
Fill the directory/folder name and copy and Paste your sound to your raw folder.
50
Android Manifest File
Whatever component you develop as a part of your application, you must declare all its components in
a manifest.xml which resides at the root of the application project directory. This file works as an interface between
Android OS and your application, so if you do not declare your component in this file, then it will not be considered
by the OS. For example, a default manifest file will look like as following file:
Here <application>...</application> tags enclosed the components related to the application. Attribute
android:icon will point to the application icon available under res/drawable-hdpi. The application uses the image
named ic_launcher.png located in the drawable folders
The <activity> tag is used to specify an activity and android:name attribute specifies the fully qualified
class name of the Activity subclass and theandroid:label attributes specifies a string to use as the label for the
activity. You can specify multiple activities using <activity> tags.
The action for the intent filter is named android.intent.action.MAIN to indicate that this activity serves as
the entry point for the application. The category for the intent-filter is named android.intent.category.LAUNCHER to
indicate that the application can be launched from the device's launcher icon.
The @string refers to the strings.xml file explained below. Hence,@string/app_name refers to
the app_name string defined in the strings.xml file, which is "HelloWorld". Similar way, other strings get populated
in the application.
51
Following is the list of tags which you will use in your manifest file to specify different Android application
components:
<activity>elements for activities
<service> elements for services
<receiver> elements for broadcast receivers
<provider> elements for content providers
In adding the image to the android studio copy and paste (ctrl + c) the image for the splash screen in the
drawable folder.
52
XML: activity_main.xml
<?xml
Java version="1.0"
File: encoding="utf-8"?>
MainActivity.java
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
import android.content.Intent;
android:layout_height="match_parent"
import android.media.MediaPlayer;
android:paddingBottom="@dimen/activity_vertical_margin"
import android.support.v7.app.AppCompatActivity;
android:paddingLeft="@dimen/activity_horizontal_margin"
import android.os.Bundle;
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
public class MainActivity extends AppCompatActivity {
android:background="@drawable/newslpash"
tools:context="com.acuin.pauleglenn.t1laboratoryexercises4.MainActivity">
MediaPlayer mySound;
</RelativeLayout>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySound.start();
Thread timer = new Thread(){
@Override
protected void onPause() {
// TODO Auto-generated method
stub super.onPause();
mySound.release();
finish();
}
}
53
Create another activity for the Welcome Message. To do that right click on java folder > new>
activity>Empty Activity.
XML: activity_main.xml
54
Applying Animation
I have used the translate and alpha animation.
Step 1 – Create the anim folder on android resources folder and create the android xml file
(anim/alpha.xml) as following:
<translate
xmlns:android="http://schemas.android.com/apk/res/
XML Layout: main.xml
android" android:fromXDelta="0%"
android:toXDelta="0%"
android:fromYDelta="200%"
<?xml version="1.0" encoding="utf-8"?>
android:toYDelta="0%"
<LinearLayout
android:duration="2000"
xmlns:android="http://schemas.android.com/apk/res/android"
android:zAdjustment="top" />
android:layout_width="fill_parent"
android:layout_height="fill_parent"
</set>
android:background="@drawable/radialback"
android:layout_gravity="center"
android:id="@+id/lin_lay"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/logo"
android:background="@drawable/logo" />
</LinearLayout>
55
Step 4 – SpalshScreenActivity.java
XML Layout: activity_main.xml
import android.app.Activity;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.Window;
import android.view.animation.Animation;
import
android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
}
}
56
Laboratory Exercise 3
Problem Statement
Create an app that can display a splash screen with rotate animation from circle image. When splash
screen displays it also playing a background sound and automatically appear the other activity when the animation
stops. See the design layout below.
Requirements:
Composed of two Activity namely: MainActivity and SplashScreen
Use animation XML for defining rotation of the circle image.
Follow the design layout for the MainActivity.
Legend:
A – This is the layout design for the SplashScreen Activity and this will initially appear when the app is
running. It will automatically dismiss or close when the rotate animation is finish and display the Main
Activity layout (refer to B)
B – This is the design layout for MainActivity that composed of two buttons, a textView for title and
ImageView for Android picture.
57
Solution (Code Snippet)
A. Create a new project in Android Studio and create an empty activity with a name “SplashScreen”.
Make sure that you create a folder under Resources for “anim” and “raw”. See the figure below for
your reference.
B. Download an image and paste it to the drawable folder. The images are for circle logo and Android
picture. Make sure that the file size of each images should be at least 100KB.
C. Download any background mp3 sound file and paste it to raw folder. You can also use other format of
music as long as it is less than 1MB in file size. It is recommended to download any sound effects at
www.soundbible.com
D. Create an animation resource file under “anim” folder for rotation animation for the circle image. See
the code below.
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="460
" android:pivotX="50%"
android:pivotY="50%"
android:duration="5000"
>
</rotate>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
android:fromDegrees="460"
android:toDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>
</set>
58
E. XML Layout Design Code
59
android:layout_width="wrap_content"
android:layout_height="180dp"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:scaleType="fitXY"
android:src="@drawable/androids" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/imageView1"
android:background="@android:drawable/btn_default
" android:layout_marginTop="20dp"
android:text="Button" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/button1"
android:layout_marginTop="15dp"
android:background="@android:drawable/btn_default"
android:text="Button" />
</RelativeLayout>
F. Activity Class Code – Create a nested class for the ArrayAdapter subclass.
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.Animation;
import
android.view.animation.AnimationUtils;
import android.widget.ImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
anim1.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
60
@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
snd1.stop();
finish();
Intent intent = new Intent(SplashScreen.this,
MainActivity.class); startActivity(intent);
}
});
}
}
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
}
}
G. Android Manifest File – Make sure that you set the LAUNCHER to the SplashScreen Activity so that
this will be display first before the MainActivity.
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
</activity>
<activity android:name=".SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
61
Chapter 3
Android UI Components and Layouts
Objectives:
At the end of this chapter the student should be able to:
Learn and understand about Views and ViewGroups
Identify Unit of Measurement used in Android
Understand the different basic Components and Design Layouts
You already learned that the basic unit of an Android application is an activity. An activity displays the user
interface of your application, which may contain widgets such as buttons, labels, textboxes, and so on. Opening
the file, you will find the following contents:
62
Common Attributes Used in Views and ViewGroups
ATTRIBUTE DESCRIPTION
layout_width Specifies the width of the View or
ViewGroup
layout_height Specifies the height of the View or
ViewGroup
layout_marginTop Specifies extra space on the top side of the
View or ViewGroup
layout_marginBottom Specifies extra space on the bottom side of
the View or ViewGroup
layout_marginLeft Specifies extra space on the left side of the
View or ViewGroup
layout_marginRight Specifies extra space on the right side of the
View or ViewGroup
layout_gravity Specifies how child Views are positioned
For example, the width of the <TextView> element fills the entire width of its parent (which is the screen in
this case) using the fill_parent constant. Its height is indicated by the wrap_content constant, which means that its
height is the height of its content (in this case, the text contained within it). If you don’t want the <TextView> view
to occupy the entire row, you can set its layout_ width attribute to wrap_content, like this:
The preceding code will set the width of the view to be equal to the width of the text contained within it.
Units of Measurements
When specifying the size of an element on an Android UI, you should be aware of the following units of
measurement:
dp — Density-independent pixel. 1 dp is equivalent to one pixel on a 160 dpi screen. This is the
recommended unit of measurement when specifying the dimension of views in your layout. The 160
dpi screen is the baseline density assumed by Android. You can specify either “dp” or “dip” when
referring to a density-independent pixel.
sp — Scale-independent pixel. This is similar to dp and is recommended for specifying font sizes.
pt — Point. A point is defined to be 1/72 of an inch, based on the physical screen size.
px — Pixel. Corresponds to actual pixels on the screen. Using this unit is not recommended, as your
UI may not render correctly on devices with a different screen resolution.
63
ID
Any View object may have an integer ID associated with it, to uniquely identify the View within the tree.
When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout
XML file as a string, in the id attribute. This is an XML attribute common to all View objects (defined by the View
class) and you will use it very often. The syntax for an ID, inside an XML tag is:
The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand
the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource
name that must be created and added to our resources (in the R.java file). There are a number of other ID
resources that are offered by the Android framework. When referencing an Android resource ID, you do not need
the plus- symbol, but must add the android package namespace, like so:
With the android package namespace in place, we're now referencing an ID from the android.R resources
class, rather than the local resources class. In order to create views and reference them from the application, a
common pattern is to define a view/widget in the layout file and assign it a unique ID:
Then create an instance of the view object and capture it from the layout (typically in the onCreate() method:
Defining IDs for view objects is important when creating a RelativeLayout. In a relative layout, sibling
views can define their layout relative to another sibling view, which is referenced by the unique ID. An ID need not
be unique throughout the entire tree, but it should be unique within the part of the tree you are searching (which
may often be the entire tree, so it's best to be completely unique when possible).
64
TextView
A TextView displays text to the user and optionally allows them to edit it. A TextView is a complete text
editor, however the basic class is configured to not allow editing.
TextView Attributes
Following are the important attributes related to TextView control. You can check Android official
documentation for complete list of attributes and related methods which you can use to change these attributes
are run time.
Attribute Description
android:id This is the ID which uniquely identifies the control.
android:capitalize If set, specifies that this TextView has a textual input method and
should automatically capitalize what the user types.
Don't automatically capitalize anything – 0
Capitalize the first word of each sentence – 1
Capitalize the first letter of every word – 2
Capitalize every character - 3
android:cursorVisible Makes the cursor visible (the default) or invisible. Default is false.
android:editable If set to true, specifies that this TextView has an input method.
android:fontFamily Font family (named by string) for the text.
android:gravity Specifies how to align the text by the view's x- and/or y-axis when
the text is smaller than the view.
android:hint Hint text to display when the text is empty.
android:inputType The type of data being placed in a text field. Phone, Date, Time,
Number, Password etc.
android:maxHeight Makes the TextView be at most this many pixels tall.
android:maxWidth Makes the TextView be at most this many pixels wide.
android:minHeight Makes the TextView be at least this many pixels tall.
android:minWidth Makes the TextView be at least this many pixels wide.
android:password Whether the characters of the field are displayed as password
dots instead of themselves. Possible value either "true" or "false".
android:phoneNumber If set, specifies that this TextView has a phone number input
method. Possible value either "true" or "false".
android:text Text to display.
android:textAllCaps Present the text in ALL CAPS. Possible value either "true" or
"false".
android:textColor Text color. May be a color value, in the form of "#rgb", "#argb",
"#rrggbb", or "#aarrggbb".
android:textColorHighlight Color of the text selection highlight.
android:textColorHint Color of the hint text. May be a color value, in the form of "#rgb",
"#argb", "#rrggbb", or "#aarrggbb".
android:textIsSelectable Indicates that the content of a non-editable text can be selected.
Possible value either "true" or "false".
65
android:textSize Size of the text. Recommended dimension type for text is "sp" for
scaled-pixels (example: 15sp).
android:textStyle Style (bold, italic, bolditalic) for the text. You can use or more of
the following values separated by '|'.
normal – 0
bold – 1
italic - 2
android:typeface Typeface (normal, sans, serif, monospace) for the text. You can
use or more of the following values separated by '|'.
normal – 0
sans – 1
serif – 2
monospace - 3
This example will take you through simple steps to show how to create your own Android application using
Linear Layout and TextView.
Step Description
1 You will use Android studio to create an Android application and name it
asdemo under a package com.example.demo as explained in the Hello World
Example chapter.
2 Modify src/MainActivity.java file to add a click event.
2 Modify the default content of res/layout/activity_main.xml file to include Android UI
control.
3 No need to change default string constants at string.xml file. Android studio takes
care of default string constants.
4 Run the application to launch Android emulator and verify the result of the changes
done in the application.
66
Following is the content of the modified main activity file src/com.example.demo/MainActivity.java. This file
can include each of the fundamental lifecycle methods.
67
Following is the default content of AndroidManifest.xml
Let's try to run your demo application. I assume you had created your AVD while doing environment setup.
To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it
will display following Emulator window.
68
Button
A Button is a Push-button which can be pressed, or clicked, by the user to perform an action.
Button Attributes
Following are the important attributes related to Button control. You can check Android official
documentation for complete list of attributes and related methods which you can use to change these attributes
are run time.
Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text.
android:editable If set, specifies that this TextView has an input method.
android:text This is the Text to display.
Attribute Description
android:background This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view,
android:onClick This is the name of the method in this View's context to invoke
when the view is clicked.
android:visibility This controls the initial visibility of the view.
69
This example will take you through simple steps to show how to create your own Android application using
Linear Layout and Button.
Step Description
1 You will use Android studio IDE to create an Android application and name it
as myapplication under a package com.example.saira_000.myapplicationas explained in
the Hello World Example chapter.
2 Modify src/MainActivity.java file to add a click event.
2 Modify the default content of res/layout/activity_main.xml file to include Android UI
control.
3 No need to declare default string constants at string.xml, Android studio takes care of
default string constants.
4 Run the application to launch Android emulator and verify the result of the changes done
in the application.
Following is the content of the modified main activity file src/MainActivity.java. This file can include each of
the fundamental lifecycle methods.
70
Following will be the content of res/layout/activity_main.xml file
Following is the default content of AndroidManifest.xml and try to run your app.
71
Toast
A toast provides simple feedback about an operation in a small popup. It only fills the amount of space
required for the message and the current activity remains visible and interactive. For example, navigating away
from an email before you send it triggers a "Draft saved" toast to let you know that you can continue editing later.
Toasts automatically disappear after a timeout.
This example demonstrates everything you need for most toast notifications. You should rarely need
anything else. You may, however, want to position the toast differently or even use your own layout instead of a
simple text message. The following sections describe how you can do these things.
You can also chain your methods and avoid holding on to the Toast object, like this:
72
Laboratory Exercise 4
Problem Statement
Create an app that show your student information with your full name, course and section, Teacher name,
birthday and your address. Use TextView to display that information and it is triggered by tapping a button. Display
also your student number using Toast and triggered also by a button. See the layout given below.
Requirements:
Composed of one activity which is the MainActivity
Use TextView and a Button to display your student information
Follow the given layout design below.
Legend:
A – This is the layout design for the Main Activity that composed of TextView with a default text and two
buttons.
B – When the user taps the “Display your Information” button, it will display the student information to the
TextViews.
C – When the user taps the “Display your Student no.” button, it will display the student number using Toast.
73
Solution (Code Snippet)
A. Create a new project and use the default activity and layout. See the project structure for your guide.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textAppearance="?
android:attr/textAppearanceLarge" android:text="Full Name"
android:id="@+id/txtFullName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true
"
android:layout_alignParentRight="true
"
android:layout_alignParentEnd="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium
" android:text="Course and Section"
android:id="@+id/txtCourse"
android:layout_below="@+id/txtFullName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="27dp"
android:layout_alignRight="@+id/txtFullName"
android:layout_alignEnd="@+id/txtFullName" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textAppearance="?
android:attr/textAppearanceMedium" android:text="Teacher Name"
74
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="28dp"
android:layout_alignRight="@+id/txtCourse"
android:layout_alignEnd="@+id/txtCourse" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textAppearance="?
android:attr/textAppearanceSmall" android:text="Birthdate"
android:id="@+id/txtBday"
android:layout_below="@+id/txtTeacher"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="31dp"
android:layout_alignRight="@+id/txtTeacher"
android:layout_alignEnd="@+id/txtTeacher" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textAppearance="?
android:attr/textAppearanceSmall" android:text="Address"
android:id="@+id/txtAddress"
android:layout_below="@+id/txtBday"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="26dp"
android:layout_alignRight="@+id/txtBday"
android:layout_alignEnd="@+id/txtBday" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display your information"
android:id="@+id/btnViewDetail"
android:layout_below="@+id/txtAddress"
android:layout_marginTop="59dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/txtAddress"
android:layout_alignEnd="@+id/txtAddress" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display your Student no."
android:id="@+id/btnShowToast"
android:layout_below="@+id/btnViewDetail"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/btnViewDetail"
android:layout_alignEnd="@+id/btnViewDetail" />
</RelativeLayout>
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import
android.widget.TextView;
import android.widget.Toast;
75
Button btnInfo, btnToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
etName.setText("Chad R. Basilio");
etcours.setText("TechVoc ICT: Section
1"); etTeacher.setText("Juan Dela Cruz");
etBday.setText("December 6, 1999");
etAddress.setText("158 Capas St., Makati City");
}
});
btnToast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
76
EditText
A EditText is an overlay over TextView that configures itself to be editable. It is the predefined subclass of
TextView that includes rich editing capabilities.
Following are the important attributes related to EditText control. You can check Android official
documentation for complete list of attributes and related methods which you can use to change these attributes
are run time. Inherited from android.widget.TextView Class
Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text.
android:editable If set, specifies that this TextView has an input method.
android:text This is the Text to display.
Attribute Description
android:background This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view,
android:onClick This is the name of the method in this View's context to invoke
when the view is clicked.
android:visibility This controls the initial visibility of the view.
This example will take you through simple steps to show how to create your own Android application using
Linear Layout and EditText.
Step Description
1 You will use Android studio IDE to create an Android application and name it
as demo under a package com.example.demo as explained in the Hello World
Example chapter.
2 Modify src/MainActivity.java file to add a click event.
3 Modify the default content of res/layout/activity_main.xml file to include Android UI
control.
77
4 Define required necessary string constants in res/values/strings.xml file
5 Run the application to launch Android emulator and verify the result of the changes done
in the application.
Following is the content of the modified main activity file src/com.example.demo/MainActivity.java. This file
can include each of the fundamental lifecycle methods.
78
Following will be the content of res/layout/activity_main.xml file
79
Following is the default content of AndroidManifest.xml.
Let's try to run your demo application. I assume you had created your AVD while doing environment setup.
To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar.
Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it
will display following Emulator window
80
Event Handlers and Listeners
Events are a useful way to collect data about a user's interaction with interactive components of
Applications. Like button presses or screen touch etc. The Android framework maintains an event queue as first-
in, first-out (FIFO) basis. You can capture these events in your program and take appropriate action as per
requirements.
81
This is called when the user presses the key, releases the key, or any
movement gesture on the screen. You will use onTouch() event handler
to handle such event.
onMenuItemClick() OnMenuItemClickListener()
This is called when the user selects a menu item. You will use
onMenuItemClick() event handler to handle such event.
onCreateContextMenu() onCreateContextMenuItemListener()
This is called when the context menu is being built(as the result of a
sustained "long click)
There are many more event listeners available as a part of View class like OnHoverListener,
OnDragListener etc which may be needed for your application. So I recommend to refer official documentation for
Android application development in case you are going to develop a sophisticated app.
Touch Mode
Users can interact with their devices by using hardware keys or buttons or touching the screen. Touching
the screen puts the device into touch mode. The user can then interact with it by touching the on-screen virtual
buttons, images, etc. You can check if the device is in touch mode by calling the View class’s isInTouchMode()
method.
Focus
A view or widget is usually highlighted or displays a flashing cursor when it’s in focus. This indicates that
it’s ready to accept input from the user.
isFocusable() – it returns true or false
isFocusableInTouchMode() – checks to see if the view is focusable in touch mode. (A view may be
focusable when using a hardware key but not when the device is in touch mode)
82
Event Listeners Registration Using an Anonymous Inner Class
Here you will create an anonymous implementation of the listener and will be useful if each class is
applied to a single control only and you have advantage to pass arguments to event handler. In this approach
event handler methods can access private data of Activity. No reference is needed to call to Activity.
But if you applied the handler to more than one control, you would have to cut and paste the code for the
handler and if the code for the handler is long, it makes the code harder to maintain. Following are the simple
steps to show how we will make use of separate Listener class to register and capture click event. Similar way you
can implement your listener for any other required event type.
Step Description
1 You will use Android studio IDE to create an Android application and name it
as myapplication under a package com.example.myapplication as explained in
the Hello World Example chapter.
2 Modify src/MainActivity.java file to add click event listeners and handlers for the two
buttons defined.
3 Modify the detault content of res/layout/activity_main.xml file to include Android UI
controls.
4 No need to declare default string constants.Android studio takes care default
constants.
5 Run the application to launch Android emulator and verify the result of the changes
done in the aplication.
progress;
Button b1,b2;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = new ProgressDialog(this);
83
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById(R.id.textView);
txtView.setTextSize(25);
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById(R.id.textView);
txtView.setTextSize(55);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present. getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in
//noinspection
SimplifiableIfStatement if (id ==
R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event Handling "
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"/>
<TextView
84
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fasttrack IT Academy "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small font"
android:id="@+id/button"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" /
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Font"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignRight="@+id/button
"
android:layout_alignEnd="@+id/button"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:textSize="25dp" />
85
Following is the default content of AndroidManifest.xml and try to run your app.
86
Laboratory Exercise 5
Problem Statement
Create an app that can perform the basic arithmetic operation of a given two floating numbers. Display the
answer using TextView with at least two decimal places. Each arithmetic operation is represented by a button.
See the layout below.
Requirements:
Composed of only activity which is the “MainActivity”
Use TextView to display the computed value.
Use button to trigger the different arithmetic operations. Use OnClick method instead of anonymous
objects for event handler for button.
Legend:
A – This is the layout design for the Main Activity where it displays the computer answer at the button.
B – Display the number keypad for entering text in the EditText.
C – When the user taps on any button for specifier arithmetic operators it will display the answer at the
TextView at the bottom.
87
Solution (Code Snippet)
A. Create a new project and use the default activity name “MainActivity”. See the project structure below
for your guide.
B. In the MainActivity.java create a method name calculateOper() (below the onCreate method) and we
will point this method on the onClick property of the Button.
C. XML Layout Design Code
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Simple Calculator"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="25dp"
android:gravity="center_horizontal"
android:id="@+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:inputType="number|
numberDecimal|numberSigned" android:ems="10"
android:id="@+id/etxtfnum"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="24dp"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:hint="First number"
android:background="@android:drawable/editbox_background" />
88
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number|numberDecimal|numberSigned"
android:ems="10"
android:id="@+id/etxtsnum"
android:layout_marginTop="21dp"
android:layout_below="@+id/etxtfnum"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/etxtfnum"
android:layout_alignEnd="@+id/etxtfnum"
android:hint="Second number"
android:background="@android:drawable/editbox_background" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Addition"
android:id="@+id/btnAdd"
android:layout_marginTop="26dp"
android:layout_below="@+id/etxtsnum"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/etxtsnum"
android:layout_alignEnd="@+id/etxtsnum"
android:onClick="calculateOper" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Substraction"
android:id="@+id/btnSub"
android:layout_below="@+id/btnAdd"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/btnAdd"
android:layout_alignEnd="@+id/btnAdd"
android:onClick="calculateOper" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Multiplication"
android:id="@+id/btnMul"
android:layout_below="@+id/btnSub"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/btnSub"
android:layout_alignEnd="@+id/btnSub"
android:onClick="calculateOper" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Division"
android:id="@+id/btnDiv"
android:layout_below="@+id/btnMul"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/btnMul"
android:layout_alignEnd="@+id/btnMul"
android:onClick="calculateOper" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Answer: No Value"
android:id="@+id/txtViewAns"
android:layout_below="@+id/btnDiv"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="30dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
89
</RelativeLayout>
import android.support.v7.app.AppCompatActivity;
In import android.os.Bundle;
this code, when the four buttons for arithmetic operations taps, the method calculateOper() will be
import android.view.View;
import android.widget.Button;
execute
import and performs a computations of the two numbers.
android.widget.EditText;
import
android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAddW = (Button)
findViewById(R.id.btnAdd); btnSubW =
(Button) findViewById(R.id.btnSub); btnMulW =
(Button) findViewById(R.id.btnMul); btnDivW =
(Button) findViewById(R.id.btnDiv);
if (view == btnAddW)
{ answer = fnum +
snum;
} else if (view == btnSubW)
{ answer = fnum - snum;
} else if (view == btnMulW)
{ answer = fnum *
snum;
} else if (view == btnDivW) {
90
E. Android Manifest File
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
91
Linear Layout
A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length
of the window exceeds the length of the screen.
LinearLayout Attributes
Following are the important attributes specific to LinearLayout:
Attribute Description
android:id This is the ID which uniquely identifies the layout.
android:baselineAligned This must be a boolean value, either "true" or "false"
and prevents the layout from aligning its children's
baselines.
android:baselineAlignedChildIndex When a linear layout is part of another layout that is
baseline aligned, it can specify which of its children to
baseline align
android:divider This is drawable to use as a vertical divider between
buttons. You use a color value, in the form of "#rgb",
"#argb", "#rrggbb", or "#aarrggbb".
android:gravity This specifies how an object should position its content,
on both the X and Y axes. Possible values are top,
bottom, left, right, center, center_vertical,
center_horizontal etc.
android:orientation This specifies the direction of arrangement and you will
use "horizontal" for a row, "vertical" for a column. The
default is horizontal.
android:weightSum Sum up of child weight
92
This example will take you through simple steps to show how to create your own Android application using
Linear Layout. Follow the following steps to modify the Android application we created in Hello World Example.
Step Description
1 You will use Android Studio to create an Android application and name it asDemo under
a package com.example.demo as explained in the Hello World Example chapter.
2 Modify the default content of res/layout/activity_main.xml file to include few buttons in
linear layout.
3 No need to change string Constants.Android studio takes care of default strings
4 Run the application to launch Android emulator and verify the result of the changes
done in the application.
Following is the content of the modified main activity file src/com.example.demo/MainActivity.java. This file
can include each of the fundamental lifecycle methods.
93
Following will be the content of res/layout/activity_main.xml file
Following will be the content of res/values/strings.xml to define two new constants and let us try to run.
Another example layout code and its output using Linear Layout.
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="To" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject" />
<EditText
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
94
android:gravity="top"
android:hint="Message" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Send" />
</LinearLayout>
Relative Layout
Enables you to specify the location of child objects relative to each other (child A to the left of child B) or to
the parent (aligned to the top of the parent).
95
Positioning Views
Relative Layout lets child views specify their position relative to the parent view or to each other (specified
by ID). So you can align two elements by right border, or make one below another, centered in the screen,
centered left, and so on. By default, all child views are drawn at the top-left of the layout, so you must define the
position of each view using the various layout properties available from RelativeLayout.LayoutParams.
Some of the many layout properties available to views in a Relative Layout include:
If "true", makes the top edge of this view match the top edge of the parent.
Positions the left edge of this view to the right of the view specified with a resource ID.
These are just a few examples. All layout attributes are documented at RelativeLayout.LayoutParams.
The value for each layout property is either a Boolean to enable a layout position relative to the parent Relative
Layout or an ID that references another view in the layout against which the view should be positioned.
In your XML layout, dependencies against other views in the layout can be declared in any order. For
example, you can declare that "view1" be positioned below "view2" even if "view2" is the last view declared in the
hierarchy. The example below demonstrates such a scenario.
96
This is the actual design output given the xml above.
During runtime, you load the XML UI in the onCreate() method handler in your Activity class, using the
setContentView() method of the Activity class, as shown in the snippet below:
97
Table Layout
TableLayout is a ViewGroup that displays child View elements in rows and columns.
TableLayout positions its children into rows and columns. TableLayout containers do not display border
lines for their rows, columns, or cells. The table will have as many columns as the row with the most cells. A table
can leave cells empty, but cells cannot span columns, as they can in HTML.
TableRow objects are the child views of a TableLayout (each TableRow defines a single row in the table).
Each row has zero or more cells, each of which is defined by any kind of other View. So, the cells of a row may be
composed of a variety of View objects, like ImageView or TextView objects. A cell may also be a ViewGroup
object (for example, you can nest another TableLayout as a cell). The following sample layout has two rows and
two cells in each. The accompanying screenshot shows the result, with cell borders displayed as dotted lines
(added for visual effect).
98
This is the graphical output.
99
Laboratory Exercise 6
Problem Statement
Create an app and design a Photo Album layout using different Layout Classes. Display at least 6 music
albums of different artists and arrange these images in a 2 x 3 table. See the layout below.
Requirements:
Composed of one Activity and use the default name for XML layout.
Display at least 6 images for Music Albums of different artists and arrange it in a table layout.
Use ScrollviewLayout and TableViewLayout for this exercise.
Test and run your app using emulator
100
Solution (Code Snippet)
A. Create new project using Android Studio and use the default names for activity and XML layout. See
the project structure below for your guide.
B. Download at least 6 images for Music Album of different sing artists using browser and paste it to the
Drawable folder. Make sure that the file size of each images should be at least 100KB.
C. XML Layout Design Code – Use ScrollViewLayout as your parent layout and the child layout is
TableLayout. Arrange the different images with equal width. See the component tree for your guide.
101
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="0dp"
android:layout_height="180dp"
android:id="@+id/imageView"
android:layout_weight="1"
android:src="@drawable/album1"
android:background="@color/material_blue_grey_800"
/>
<ImageView
android:layout_width="0dp"
android:layout_height="180dp"
android:id="@+id/imageView2"
android:layout_weight="1"
android:src="@drawable/album2"
android:background="@color/material_deep_teal_200" /
>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="0dp"
android:layout_height="180dp"
android:id="@+id/imageView3"
android:layout_weight="1"
android:src="@drawable/album3"
android:background="@color/material_deep_teal_200" /
>
<ImageView
android:layout_width="0dp"
android:layout_height="180dp"
android:id="@+id/imageView4"
android:layout_weight="1"
android:src="@drawable/album4"
android:background="@color/material_blue_grey_800" /
>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="0dp"
android:layout_height="180dp"
android:id="@+id/imageView5"
android:layout_weight="1"
android:src="@drawable/album5"
android:background="@color/material_blue_grey_800" /
>
<ImageView
android:layout_width="0dp"
android:layout_height="180dp"
android:id="@+id/imageView6"
android:layout_weight="1"
android:src="@drawable/album6"
102
D. Activity Class Code
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
}
}
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
103
Radio Buttons
A RadioGroup class is used for set of radio buttons. If we check one radio button that belongs to a radio
group, it automatically unchecks any previously checked radio button within the same group.
RadioGroup Attributes
Following are the important attributes related to RadioGroup control. You can check Android official
documentation for complete list of attributes and related methods which you can use to change these attributes
are run time.
Attribute Description
android:checkedButton This is the id of child radio button that should be checked by default
within this radio group.
Attribute Description
android:background This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view,
android:onClick This is the name of the method in this View's context to invoke
when the view is clicked.
android:visibility This controls the initial visibility of the view.
This example will take you through simple steps to show how to create your own Android application using
Linear Layout and RadioGroup.
Step Description
1 You will use Android studio IDE to create an Android application and name it as My
Application under a packagecom.example.saira_000.myapplication; as explained in
the Hello World Example chapter.
2 Modify src/MainActivity.java file to add a click event.
2 Modify the default content of res/layout/activity_main.xml file to include Android UI
control.
104
3 No need to change default constants at res/values/strings.xml, android studio takes care
of default constants.
4 Run the application to launch Android emulator and verify the result of the changes done
in the application.
Following is the content of the modified main activity file src/MainActivity.java. This file can include each of
the fundamental lifecycle methods.
import
android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import
android.view.MenuItem;
import android.view.View;
import
android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioSexGroup=(RadioGroup)findViewById(R.id.radioGroup);
btnDisplay=(Button)findViewById(R.id.button);
btnDisplay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selectedId=radioSexGroup.getCheckedRadioButtonId();
radioSexButton=(RadioButton)findViewById(selectedId);
Toast.makeText(MainActivity.this,radioSexButton.getText(),
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
105
}
return super.onOptionsItemSelected(item);
}
}
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radio button"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fasttrack IT Academy"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:textSize="35dp"
android:textColor="@android:color/holo_green_dark" /
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView" /
>
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="90dp"
android:layout_below="@+id/imageView"
android:layout_marginTop="58dp"
android:weightSum="1"
android:id="@+id/radioGroup"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2
"
android:layout_alignRight="@+id/textView3
"
android:layout_alignEnd="@+id/textView3"
>
106
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:id="@+id/radioButton2"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp"
android:layout_weight="0.13" />
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Are you?"
android:id="@+id/textView3"
android:textSize="35dp"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_gravity="center_horizontal"
android:layout_below="@+id/radioGroup"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.My Application.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
107
</activity>
</application>
</manifest>
Checkbox
A CheckBox is an on/off switch that can be toggled by the user. You should use check-boxes when
presenting users with a group of selectable options that are not mutually exclusive.
CheckBox Attributes
Following are the important attributes related to CheckBox control. You can check Android official
documentation for complete list of attributes and related methods which you can use to change these attributes
are run time.
108
Inherited from android.view.View Class
Attribute Description
android:background This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view,
android:onClick This is the name of the method in this View's context to invoke
when the view is clicked.
android:visibility This controls the initial visibility of the view.
This example will take you through simple steps to show how to create your own Android application using
Linear Layout and CheckBox.
Step Description
1 You will use Android Studio IDE to create an Android application and name it
as myapplication under a package com.example.myapplication as explained in
the Hello World Example chapter.
2 Modify src/MainActivity.java file to add a click event.
2 Modify the default content of res/layout/activity_main.xml file to include Android UI
control.
3 No need to declare default string constants. Android studio takes care of default
constants at string.xml
4 Run the application to launch Android emulator and verify the result of the changes
done in the application.
Following is the content of the modified main activity file src/MainActivity.java. This file can include each of
the fundamental lifecycle methods.
import android.os.Bundle;
import
android.app.Activity;
import android.view.Menu;
import android.view.View;
import
android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.Toast;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
109
ch2=(CheckBox)findViewById(R.id.checkBox2);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View
v) { finish();
}
});
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("Thanks : ").append(ch1.isChecked());
result.append("\nThanks: ").append(ch2.isChecked());
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present. getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="@+id/">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example of checkbox"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do you like Tutorials Point"
android:layout_above="@+id/button"
android:layout_centerHorizontal="true" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content
"
android:layout_height="wrap_content
" android:text="Do you like android "
110
android:layout_alignLeft="@+id/checkBox1"
android:layout_alignStart="@+id/checkBox1" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/checkBox1"
android:layout_below="@+id/textView1"
android:layout_marginTop="39dp"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/checkBox
1"
android:layout_alignStart="@+id/checkBox1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:id="@+id/button2"
android:layout_alignParentBottom="true"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" /
>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" /
Following
<?xml is the default
version="1.0" content of AndroidManifest.xml and try to run the app.
encoding="utf-8"?>
<resources>
<?xml version="1.0"
<string encoding="utf-8"?>
name="app_name">MyApplication</string>
<string name="action_settings">Settings</string>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
</resources>
package="com.example.myapplication">
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.myapplication.MainActivity"
111
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
112
Laboratory Exercise 7
Problem Statement
Create an app that display the list of fruits based on the check item in the Checkbox lists namely Apple,
Banana and Grapes. Your app is also can change the color background by selected a specified color represented
by a radio button. The colors are white, red, blue and yellow. See the layout below.
Requirements:
Composed of one activity name “MainActivity”
Use Checkbox and Radio button for this exercise.
Follow the given layout design below.
Legend:
A – This is the layout design for the Main Activity where it displays the three checkbox for different fruits
and lists for radio button color for changing background color of the layout.
B – When the user taps select fruits it will display on the TextView and at the same time it will change the
background color for selected radio button color.
113
Solution (Code Snippet)
A. Create a new project in android studio and use the default name for MainActivity. See the project
structure for your guide.
B. XML Layout Design Code – Design the layout for checkbox and radio button. Use RadioGroup
container for the different colors of radio button so that only one color can be selected. See the
component tree for your guide.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
114
<CheckBox
android:id="@+id/checkBoxApple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onCheckboxClicked"
android:text="Apple"
android:checked="false" />
<CheckBox
android:id="@+id/checkBoxBanana"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onCheckboxClicked"
android:text="Banana"
android:checked="false" />
<CheckBox
android:id="@+id/checkBoxGrapes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onCheckboxClicked"
android:text="Grapes"
android:checked="false" />
</LinearLayout>
<TextView
android:id="@+id/txtResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="20dp"
android:text="Checked items: No Value"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose background color:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radioWhite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:onClick="onRadioButtonClicked"
android:text="White" />
<RadioButton
android:id="@+id/radioRed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:onClick="onRadioButtonClicked"
android:text="Red" />
<RadioButton
android:id="@+id/radioBlue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonClicked"
android:text="Blue" />
<RadioButton
android:id="@+id/radioYellow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonClicked"
android:text="Yellow"
android:checked="false" />
115
</RadioGroup>
</LinearLayout>
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import
android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for checkBox
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
String fruitCheckStr =
""; if(ckApple) {
fruitCheckStr = "Apple, ";
}
if(ckBanana) {
fruitCheckStr += "Banana, ";
}
116
if(ckGrape) {
fruitCheckStr += "Grape ";
}
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
117
ImageView
In Android, you can use “android.widget.ImageView” class to display an image file. Image file is easy to
use but hard to master, because of the various screens and dpi in Android devices. At the simplest level, an
ImageView is simply a view you embed within an XML layout that is used to display an image (or any drawable) on
the screen. The ImageView looks like this in res/layout/activity_main.xml:
The ImageView handles all the loading and scaling of the image for you. Note the scaleType attribute
which defines how the images will be scaled to fit in your layout. In the example, using scaleType "center", the
image will be displayed at its native resolution and centered in the view, regardless of how much space the view
consumes.
The scaleType above has been set to fitXY which sets the height and the width up or down to fit the
maximum dimensions specified. Fixing the width and height however means that the proportions of the width and
height of the original image, known as the aspect ratio, will be altered. We can take advantage of the
adjustViewBounds parameter to preserve this aspect ratio. However, we must either allow the height and/or width
to be adjustable (i.e. by using maxWidth and using wrap_content for the dimension). Otherwise, the dimensions
cannot be readjusted to meet the required aspect ratio.
118
By combining these properties together, we can control the rough size of the image and still adjust the
image according to the proper aspect ratio. We can also size an ImageView at runtime within our Java source
code by modifying the width or height inside getLayoutParams() for the view:
In certain cases, the image needs to be scaled to fit the parent view's width and the height should be
adjusted proportionally. We can achieve this using an extended ResizableImageView class as described in the
post.
Scale Types
An ImageView can display an image differently based on the scaleType provided. Above we discussed
the fitXY type along with adjustViewBounds to match the aspect ratio of the drawable. The following is a list of all
the most common types:
119
Note that the fitXY scale type allows you to set the exact size of the image in your layout. However, be
mindful of potential distortions of the image due to scaling. If you’re creating a photo-viewing application, you will
probably want to use the center or fitCenter scale types.
This means that if you generate a 100x100 for mdpi (1x baseline), then you should generate the same
resource in 150x150 for hdpi (1.5x), 200x200 image for xhdpi devices (2.0x), 300x300 image for xxhdpi (3.0x) and
a 75x75 image for ldpi devices (0.75x). See these density guidelines for additional details.
This handy utility allows us to select a resources directory, choose an extra high density image and the
tool will automatically generate the corresponding lower size images for us and place them in the correct folders.
See
120
the screens support reference for a more detailed look at supporting a wide range of devices. Also check out
the iconography guide for more details.
Mipmap image resources can then be accessed using the @mipmap/ic_launcher notation in place of
@drawable. Placing icons in mipmap folders (rather than drawable) is considered a best practice because they
can often be used at resolutions different from the device’s current density. For example, an xxxhdpi app icon
might be used on the launcher for an xxhdpi device.
Scaling a Bitmap
If we need to resize a Bitmap, we can call the createScaledBitmap method to resize any bitmap to our
desired width and height:
121
You often want to resize a bitmap but preserve the aspect ratio using a BitmapScaler utility class with
code like this:
In other cases, you may want to determine the device height or width in order to resize the image
accordingly. Copy this in your project and use anywhere that you have a context to determine the screen
dimensions:
Note: Doing any type of scaling of images results in the loss of EXIF metadata that includes info such as camera,
rotation, date/time of the photo taken. While there are workarounds to transfer this data after the image has been
copied, there are current limitations. If you need this info or wish to upload it to some site, you should send the
original file and not the down sampled version.
122
Spinner
Spinner allows you to select an item from a drop down menu. For example, when you are using Gmail
application you would get drop down menu as shown below, you need to select an item from a drop down menu.
This example demonstrates the category of computers; you need to select a category from the category.
To experiment with this example, you need to run this on an actual device on after developing the application
according to the steps below.
Steps Description
1 You will use Android studio to create an Android application and name it as
AndroidSpinnerExample under a package com.example.spinner. While creating this
project, make sure you Target SDK and Compile With at the latest version of Android
SDK to use higher levels of APIs.
2 Modify src/AndroidSpinnerExampleActivity.java file to create a simple list view with items
which are showing as spinner items
3 Modify res/layout/activity_main.xml file to add respective XML code.
4 No need to define default string constants. Android studio takes care of default string
constants at string.xml
5 Run the application and choose a running android device and install the application on it
and verify the results.
import
java.util.ArrayList;
import java.util.List;
import
android.app.Activity;
import
android.os.Bundle;
import
123
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
@Override
public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinner);
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Category:"
android:layout_marginBottom="5dp"/>
124
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/spinner_title"/>
</LinearLayout>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.spinner.AndroidSpinnerExampleActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
125
Laboratory Exercise 8
Problem Statement
Create an app that can pick a specific image from four different avatar images using dropdown spinner.
When a user selects a particular image it will show the avatar using ImageView. See the sample output below.
Requirements:
Composed of one activity called “MainActivity”
Use Spinner to display four different avatar image items and display the actual image using ImageView.
Follow the design layout given below.
Legend:
A – This is the layout design for the Main Activity that composed of spinner and an Image view. The default
image is the ic_launcher from mipmap folder.
B – When the user taps the spinner it will display all the four avatar images in a dropdown.
C – When the user selected a particular item in the spinner it will automatically display/load the image to
the image view.
126
Solution (Code Snippet)
A. Create a new project using Android Studio and select the Empty activity. See the project structure for your
guide.
B. Download at least 4 avatar images/icon using browser and paste it to the Drawable folder. Make sure that
the file size of each images should be at least 100KB.
C. XML Layout Design Code
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:id="@+id/imgRes"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="38dp"
android:src="@mipmap/ic_launcher" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/spinImage"
android:layout_below="@+id/imgRes"
android:layout_marginTop="33dp"
android:background="@android:drawable/
spinner_dropdown_background" android:spinnerMode="dropdown"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
127
D. Activity Class Code – Create a nested class for the ArrayAdapter subclass.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import
android.widget.AdapterView;
import
android.widget.ArrayAdapter;
import
android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
ImageView imgPic;
Spinner spinPic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinPic.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
imgPic.setImageResource(R.mipmap.ic_launcher);
Toast.makeText(getApplicationContext(), "Select other image",
Toast.LENGTH_LONG).show();
brea
k; case
1:
imgPic.setImageResource(R.drawable.biopic)
; break;
case 2:
imgPic.setImageResource(R.drawable.controlpic);
break;
case 3:
imgPic.setImageResource(R.drawable.maskpic);
break;
case 4:
imgPic.setImageResource(R.drawable.spiderpic);
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
128
E. Android Manifest File
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
129
Seekbar
This section demonstrates how to use the SeekBar control. The SeekBar control is visually similar to the
ProgressBar but it has a draggable slider that will allow the user to change the value displayed by the control. This
will provide an example showing how to respond to changes in the SeekBar using events or the
SeekBar.setOnSeekBarChangeListener().
The SeekBar widget is an interactive slider that allows the user to select one value from a range of values.
As the user moves the slider left or right, the value of the SeekBar will change. The following image shows an
example of the SeekBar:
A SeekBar is added to the layout of an Activity or a Fragment. The following snippet is an example of
the SeekBar XML:
This code snippet shows an example of attaching a lambda to the SeekBar.ProgressChanged event:
130
This lambda will update a TextView widget with the value of the SeekBar when the change is triggered by
the user. The following screen shot is an example of what an Activity might look like after the user has moved the
slider:
131
Toggle Button
A ToggleButton displays checked/unchecked states as a button. It is basically an on/off button with a light
indicator.
ToggleButton Attributes
Following are the important attributes related to ToggleButton control. You can check Android official
documentation for complete list of attributes and related methods which you can use to change these attributes
are run time.
Attribute Description
android:disabledAlpha This is the alpha to apply to the indicator when disabled.
android:textOff This is the text for the button when it is not checked.
android:textOn This is the text for the button when it is checked.
132
This example will take you through simple steps to show how to create your own Android application using
Linear Layout and ToggleButton.
Step Description
1 You will use Android studio IDE to create an Android application and name it as My
Application under a package com.example.saira_000.myapplicationas explained in
the Hello World Example chapter.
2 Modify src/MainActivity.java file to add a click event.
2 Modify the default content of res/layout/activity_main.xml file to include Android UI
control.
3 No need to declare default constants.Android studio takes care of default constants at
string.xml
4 Run the application to launch Android emulator and verify the result of the changes
done in the application.
Following is the content of the modified main activity file src/MainActivity.java. This file can include each of
the fundamental lifecycle methods.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import
android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.Toast;
import android.widget.ToggleButton;
tg1=(ToggleButton)findViewById(R.id.toggleButton);
tg2=(ToggleButton)findViewById(R.id.toggleButton2);
b1=(Button)findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("You have clicked first ON Button-:) ").append(tg1.getText());
result.append("\You have clicked Second ON Button -:) ").append(tg2.getText());
Toast.makeText(MainActivity.this, result.toString(),Toast.LENGTH_SHORT).show();
}
});
133
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present. getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in
AndroidManifest.xml. int id = item.getItemId();
//noinspection
SimplifiableIfStatement if (id ==
R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" /
>
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="On"
android:id="@+id/toggleButton"
android:checked="true"
android:layout_below="@+id/imageButton"
android:layout_toLeftOf="@+id/imageButton"
android:layout_toStartOf="@+id/imageButton"
/>
<ToggleButton
134
android:id="@+id/toggleButton2"
android:checked="true"
android:layout_alignTop="@+id/toggleButton"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="ClickMe"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.My Application.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
135
Laboratory Exercise 9
Problem Statement
Create an app that can compute the average of four subjects namely Science, Mathematics, English and
Programming. The grade can be set using SeekBar and set the grade from 50% to 100%. The toggle button can
set if the subject grade is included or not included in the average grade computation. Display the average grade
using TextView at bottom of the app. See the sample output below.
Requirements:
Composed of only one activity with a name of “MainActivity” by default.
Use Seekbar to set the subject grade and toggle button to set if the grade is included in the average
computation or not.
Use button to trigger the computation and display the average result at the bottom.
Legend:
A – This is the layout design for the Main Activity all the grades are set to 50% by default and all the toggle
buttons are set to “not included”.
B – This is the sample computation of average grade when all the grades are included.
C – This is the sample computation of average grade when some of the grades are included.
136
Solution (Code Snippet)
A. Create a new project using Android Studio and see the project structure below for your guide.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student Grade Evaluation"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="25dp"
android:gravity="center_horizontal"
android:id="@+id/textView" />
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/seekSci"
android:layout_marginTop="58dp"
android:layout_below="@+id/textView"
android:layout_toLeftOf="@+id/toggleSci"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:max="50"
android:progress="0"
android:indeterminate="false" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="@+id/toggleSci"
android:layout_alignBottom="@+id/seekS
ci"
android:layout_alignRight="@+id/textView
137
android:textOn="Included"
android:checked="false" />
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/seekMath"
android:layout_marginTop="52dp"
android:layout_below="@+id/seekSci"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/seekSci"
android:layout_alignEnd="@+id/seekSci"
android:max="50"
android:indeterminate="false"
android:progress="0" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="@+id/toggleMath"
android:layout_alignBottom="@+id/seekMath"
android:layout_alignLeft="@+id/toggleSci"
android:layout_alignStart="@+id/toggleSci"
android:textOff="Not Included"
android:textOn="Included"
android:checked="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Science: 50%"
android:id="@+id/txtSci"
android:layout_alignTop="@+id/toggleSci"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/seekSci"
android:layout_alignEnd="@+id/seekSci" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Mathematics: 50%"
android:id="@+id/txtMath"
android:layout_alignTop="@+id/toggleMath"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/seekMath"
android:layout_alignEnd="@+id/seekMath" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="@+id/toggleEng"
android:layout_below="@+id/toggleMath"
android:layout_alignLeft="@+id/toggleMath"
android:layout_alignStart="@+id/toggleMath"
android:layout_marginTop="27dp"
android:textOff="Not Included"
android:textOn="Included"
android:checked="false" />
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/seekEng"
android:layout_alignBottom="@+id/toggleEng"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/seekMath"
android:layout_alignEnd="@+id/seekMath"
android:max="50"
android:indeterminate="false"
138
android:progress="0" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="English: 50%"
android:id="@+id/txtEng"
android:layout_alignTop="@+id/toggleEng"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/seekEng"
android:layout_alignEnd="@+id/seekEng" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="@+id/toggleProg"
android:layout_marginTop="32dp"
android:layout_below="@+id/toggleEng"
android:layout_alignLeft="@+id/toggleEng"
android:layout_alignStart="@+id/toggleEng"
android:textOff="Not Included"
android:textOn="Included"
android:checked="false" />
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/seekProg"
android:layout_alignBottom="@+id/toggleProg"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/seekEng"
android:layout_alignEnd="@+id/seekEng"
android:max="50"
android:indeterminate="false"
android:progress="0" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Programming: 50%"
android:id="@+id/txtProg"
android:layout_above="@+id/seekProg"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/seekProg"
android:layout_alignEnd="@+id/seekProg" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CALCULATE"
android:id="@+id/btnCalc"
android:layout_below="@+id/seekProg"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="31dp"
android:layout_alignRight="@+id/toggleProg"
android:layout_alignEnd="@+id/toggleProg" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Average: No Grade"
android:id="@+id/txtResult"
android:layout_below="@+id/btnCalc"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/btnCalc"
android:layout_alignEnd="@+id/btnCalc"
android:layout_marginTop="10dp"
android:textColor="#2a34f4" />
139
</RelativeLayout>
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import
android.widget.SeekBar;
import
android.widget.TextView;
import android.widget.ToggleButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int countGrd = 0;
float totalGrd = 0;
if
(togSci.isChecked
()) { countGrd++;
totalGrd = totalGrd + skSci.getProgress() + 50;
}
if (togEng.isChecked())
{ countGrd++;
totalGrd = totalGrd + skEng.getProgress() + 50;
}
if (togMath.isChecked()) {
countGrd++;
totalGrd = totalGrd + skMath.getProgress() + 50;
}
if (togPro.isChecked()) {
140
etRes.setText("Average: No Grade");
} else {
float ave = totalGrd / countGrd;
etRes.setText("Average: " + String.format("%.2f%%", ave));
}
}
});
//Science grade
skSci.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int grd = progressChanged + 50;
etSci.setText("Science: " + grd + "%");
}
});
//English Grade
skEng.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int grd = progressChanged + 50;
etEng.setText("English: " + grd + "%");
}
});
//Math Grade
skMath.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int grd = progressChanged + 50;
etMath.setText("Mathematics: " + grd + "%");
}
141
});
//Programming Grade
skPro.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged =
0; @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
@Override
public void onStopTrackingTouch(SeekBar seekBar)
{ int grd = progressChanged + 50;
etPro.setText("Programming: " + grd + "%");
}
});
}
}
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
142
Switch
Android 4 introduced a Switch widget (shown below) that allows a user to toggle between two states, such
as ON or OFF. The Switch default value is OFF. The widget is shown below in both its ON and OFF states:
143
Providing a Title
The Switch widget also supports including a text label by setting the text attribute as follows:
ProgressBar
Progress bars are used to show progress of a task. For example, when you are uploading or downloading
something from the internet, it is better to show the progress of download/upload to the user.
In android there is a class called ProgressDialog that allows you to create progress bar. In order to do this, you
need to instantiate an object of this class. Its syntax is.
Now you can set some properties of this dialog. Such as, its style, its text etc.
144
Apart from these methods, there are other methods that are provided by the ProgressDialog class
Sr. No Title and description
1 getMax()
This method returns the maximum value of the progress.
2 incrementProgressBy(int diff)
This method increments the progress bar by the difference of value passed as a parameter.
3 setIndeterminate(boolean indeterminate)
This method sets the progress indicator as determinate or indeterminate.
4 setMax(int max)
This method sets the maximum value of the progress dialog.
5 setProgress(int value)
This method is used to update the progress dialog with some specific value.
6 show(Context context, CharSequence title, CharSequence message)
This is a static method, used to display progress dialog.
This example demonstrates the horizontal use of the progress dialog which is in fact a progress bar. It
displays a progress bar on pressing the button. To experiment with this example, you need to run this on an actual
device after developing the application according to the steps below.
Steps Description
1 You will use Android studio to create an Android application under a package
com.example.sairamkrishna.myapplication. While creating this project, make sure you
Target SDK and Compile With at the latest version of Android SDK to use higher levels of
APIs.
2 Modify src/MainActivity.java file to add progress code to display the progress dialog.
3 Modify res/layout/activity_main.xml file to add respective XML code.
4 Run the application and choose a running android device and install the application on it and
verify the results.
import
android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Color;
import
android.graphics.drawable.BitmapDrawable;
import
android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
145
public class MainActivity extends AppCompatActivity
{ Button b1;
private ProgressDialog progress;
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content
" android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="tru
e" android:textSize="30dp"
android:text="Progress bar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fasttrack IT Academy"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
146
android:text="Download"
android:onClick="download"
android:id="@+id/button2"
android:layout_marginLeft="125dp"
android:layout_marginStart="125dp"
android:layout_centerVertical="true" />
</RelativeLayout>
This is the default AndroidManifest.xml and let’s try to run the app.
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launche
r"
android:label="@string/app_name"
android:theme="@style/AppTheme"
>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter></activity>
</application>
147
Laboratory Exercise 10
Problem Statement
Create an app can computer a summation of a given numbers from 1 to 9. Each number is represented by
a switch where if it is on it is included in the summation. When the button taps the summation result will display at
the bottom part of the design using a Text view. See the sample output below.
Requirements:
Composed of only one activity named “MainActivity”
Use Switch that represents a number from 1 – 9. The switches are arranged using the TableLayout.
Use button to trigger to answer from the summation.
Legend:
A – This is the layout design for the Main Activity where all the switches from 1 to 9 are arranged in a Table
form. By default, all number switches are turned OFF.
B – When the user switch ON a specific number it is included in the computation of the number. In this
example the ON are 4, 2 and 3 which is the summation are 9.
C – When all the numbers are switched ON the summation result is 45.
148
Solution (Code Snippet)
A. Create a new project using Android Studio and see the project structure below for your guide.
B. XML Layout Design Code – All the switches are arrange using TableLayout. See the component tree
below for your guide.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Summation of Numbers"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="25dp"
android:gravity="center_horizontal"
android:id="@+id/textView"
android:layout_marginBottom="20dp"/>
149
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/tableLayout">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/switch1"
android:checked="false"
android:layout_weight="1"
android:text="1"
android:background="#f5d3d3"
android:textSize="20dp" />
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:id="@+id/switch2"
android:checked="false"
android:layout_weight="1"
android:background="#d7d5d5"
android:textSize="20dp" />
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:id="@+id/switch3"
android:checked="false"
android:layout_weight="1"
android:background="#f5d3d3"
android:textSize="20dp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4"
android:id="@+id/switch4"
android:checked="false"
android:layout_weight="1"
android:background="#d7d5d5"
android:textSize="20dp" />
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5"
android:id="@+id/switch5"
android:checked="false"
android:layout_weight="1"
android:background="#f5d3d3"
android:textSize="20dp" />
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="6"
android:id="@+id/switch6"
android:checked="false"
android:layout_weight="1"
android:background="#d7d5d5"
android:textSize="20dp" />
150
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content
" android:text="7"
android:id="@+id/switch7"
android:checked="false"
android:layout_weight="1"
android:background="#f5d3d3"
android:textSize="20dp" />
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content
" android:text="8"
android:id="@+id/switch8"
android:checked="false"
android:layout_weight="1"
android:background="#d7d5d5"
android:textSize="20dp" />
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content
" android:text="9"
android:id="@+id/switch9"
android:checked="false"
android:layout_weight="1"
android:background="#f5d3d3"
android:textSize="20dp" />
</TableRow>
</TableLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate Summation"
android:id="@+id/btnCalc"
android:layout_below="@+id/tableLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="38dp"
android:layout_alignRight="@+id/tableLayout"
android:layout_alignEnd="@+id/tableLayout" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textAppearance="?
android:attr/textAppearanceLarge" android:text="Answer: 0"
android:id="@+id/txtAnswer"
android:layout_below="@+id/btnCalc"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="34dp"
android:layout_alignRight="@+id/btnCalc"
android:layout_alignEnd="@+id/btnCalc"
android:textColor="#0410f7" />
</RelativeLayout>
151
C. Activity Class Code
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import
android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int summ = 0;
if(sw1.isChecked())
{ summ += 1;
}
if(sw2.isChecked())
{ summ += 2;
}
if(sw3.isChecked())
{ summ += 3;
}
if(sw4.isChecked())
{ summ += 4;
}
if(sw5.isChecked())
{ summ += 5;
}
if(sw6.isChecked())
{ summ += 6;
}
if(sw7.isChecked())
{ summ += 7;
}
if(sw8.isChecked())
{ summ += 8;
152
if(sw9.isChecked())
{ summ += 9;
}
}
});
}
}
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
153
AlertDialog
A Dialog is small window that prompts the user to a decision or enter additional information. Some times in
your application, if you wanted to ask the user about taking a decision between yes or no in response of any
particular action taken by the user, by remaining in the same activity and without changing the screen, you can
use Alert Dialog.
In order to make an alert dialog, you need to make an object of AlertDialogBuilder which an inner class of
AlertDialog. Its syntax is given below:
Now you have to set the positive (yes) or negative (no) button using the object of the AlertDialogBuilder
class. Its syntax is:
Apart from this, you can use other functions provided by the builder class to customize the alert dialog.
These are listed below
154
After creating and setting the dialog builder, you will create an alert dialog by calling the create() method of
the builder class. Its syntax is
Dialog fragment
Before enter into an example we should need to know dialog fragment. Dialog fragment is a fragment which
can show fragment in dialog box.
List dialog
It has used to show list of items in a dialog box. For suppose, user need to select a list of items or else
need to click an item from multiple list of items. At this situation we can use list dialog.
155
Single-choice list dialog
It has used to add single choice list to Dialog box. We can check or uncheck as per user choice.
The following example demonstrates the use of AlertDialog in android. To experiment with this example,
you need to run this on an emulator or an actual device.
Steps Description
1 You will use Android studio to create an Android application and name it as My Application
under a package package com.example.sairamkrishna.myapplication; While creating this
project, make sure you Target SDK and Compile With at the latest version of Android SDK
to use higher levels of APIs.
2 Modify src/MainActivity.java file to add alert dialog code to launch the dialog.
156
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
4 No need to change default string constants. Android studio takes care of default strings at
values/string.xml
5 Run the application and choose a running android device and install the application on it
and verify the results.
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import
android.view.MenuItem;
import android.view.View;
import
android.widget.Toast;
{ @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int
which) { finish();
}
});
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
157
int id = item.getItemId();
//noinspection
SimplifiableIfStatement if (id ==
R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alert Dialog"
android:id="@+id/textView"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorialspoint"
android:id="@+id/textView2"
android:textColor="#ff3eff0f"
android:textSize="35dp"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/logo"
android:layout_below="@+id/textView2"
android:layout_alignRight="@+id/textView2
"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alert dialog"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_marginTop="42dp"
android:onClick="open"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />
</RelativeLayout>
158
Here is the default code of AndroidManifest.xml.
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
Applying Custom Styles to Widgets
<action android:name="android.intent.action.MAIN" />
<categorydefines
A style resource android:name="android.intent.category.LAUNCHER"
the format and look for a UI. A style can/>be applied to an individual View (from
</intent-filter>
within a layout file) or to an entire Activity or application (from within the manifest file).
</activity>
</application>
Defining Styles
</manifest>
A style is defined in an XML resource that is separate from the XML that specifies the layout. This XML file
resides under res/values/ directory of your project and will have <resources> as the root node which is mandatory
for the style file. The name of the XML file is arbitrary, but it must use the .xml extension.
You can define multiple styles per file using <style> tag but each style will have its name that uniquely
identifies the style. Android style attributes are set using <item> tag as shown below
159
The value for the <item> can be a keyword string, a hex color, a reference to another resource type, or
other value depending on the style property.
Using Styles
Once your style is defined, you can use it in your XML Layout file using style attribute as follows:
Style Inheritance
Android supports style Inheritance in very much similar way as cascading style sheet in web design. You
can use this to inherit properties from an existing style and then define only the properties that you want to change
or add.
To implement a custom theme, create or edit MyAndroidApp /res/values/themes.xml and add the following
160
In your AndroidManifest.xml apply the theme to the activities you want to style
Your new theme will be applied to your activity, and text is now bright red.
161
Android Themes
Hope you understood the concept of Style, so now let's try to understand what is a Theme. A theme is
nothing but an Android style applied to an entire Activity or application, rather than an individual View. Thus, when
a style is applied as a theme, every View in the Activity or application will apply each style property that it supports.
For example, you can apply the same CustomFontStyle style as a theme for an Activity and then all text
inside that Activity will have green monospace font.To set a theme for all the activities of your application, open the
AndroidManifest.xml file and edit the <application> tag to include the android:theme attribute with the style name.
For example:
But if you want a theme applied to just one Activity in your application, then add the android:theme
attribute to the <activity> tag only. For example:
There are number of default themes defined by Android which you can use directly or inherit them using
parent attribute as follows:
162
Styling the color palette
The layout design can implementable based on them based colors, for example as following design is
designed based on them color (blue)
Above layout has designed based on style.xml file, which has placed atres/values/
163
Laboratory Exercise 11
Problem Statement
Create an app that can compute the average grade from five different subjects and display its equivalent
grade based on the table below. Use a AlertDialog to display the average and equivalent grade. Follow the design
layout below.
Average Grade Equivalent
100 – 96 Outstanding
95 – 91 Excellent
90 – 86 Good
85 – 81 Pass
80 – 75 Needs Improvement
Below 75 Failed
Above 100 Cheater!
Requirements:
Composed of one activity named “MainActivity”
Use AlertDialog Class to display the average grade and its equivalent
Design the widget with a custom design. Follow the design layout given
164
Legend:
A – This is the layout design for the Main Activity the user can enter the student name and five subject
grades. All the EditText are set with hint so that the user can know what text can be entering.
B – The grades can be type with floating values. The result button clears up the contents of the Text fields.
C – When the user taps the button “Calculate grade” it will show a dialog box and display the average
grade and its equivalent grade. Take note that average grade is formatted with at least two decimal places
only.
B. Drawable design for Custom layout design for Buttons and EditText.
<corners
android:bottomLeftRadius="5dp
"
android:bottomRightRadius="5dp
" android:topLeftRadius="5dp"
android:topRightRadius="5dp" /
>
<padding
android:left="10dp"
android:top="5dp"
android:right="10dp"
android:bottom="5dp" />
</shape>
</item>
<item>
165
android:endColor="#b9bab9"
android:startColor="#b9bab9"
android:angle="270" />
<corners
android:bottomLeftRadius="5dp
"
android:bottomRightRadius="5dp
" android:topLeftRadius="5dp"
android:topRightRadius="5dp" /
>
<padding
android:left="10dp"
android:top="5dp"
android:right="10dp"
android:bottom="5dp" />
</shape>
</item>
<corners
android:topLeftRadius="5dip"
android:topRightRadius="5dip"
android:bottomLeftRadius="5dip"
android:bottomRightRadius="5dip" />
<stroke
android:width="1dip"
android:color="#534f44"
/>
<padding
android:left="15dp"
android:top="5dp"
android:right="15dp"
android:bottom="5dp"
/>
166
XML Layout: activity_main.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Compute Grade"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="25dp"
android:gravity="center_horizontal"
android:layout_marginBottom="20dp"
android:id="@+id/textView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/txtName"
android:hint="Type your name here"
android:background="@drawable/edittext_style"
android:layout_marginBottom="5dp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Science"
android:id="@+id/textView2"
android:layout_below="@+id/txtSci"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_weight="1" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtSci"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:background="@drawable/edittext_style"
android:layout_weight="3"
android:hint="Type your grade here" />
</TableRow>
167
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Mathematics"
android:id="@+id/textView3"
android:layout_below="@+id/txtMath"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_weight="1" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtMath"
android:layout_alignTop="@+id/textView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toRightOf="@+id/textView2"
android:layout_toEndOf="@+id/textView2"
android:background="@drawable/edittext_style"
android:layout_weight="3"
android:hint="Type your grade here" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="English"
android:id="@+id/textView4"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_weight="1" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtEng"
android:layout_alignTop="@+id/textView3"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toRightOf="@+id/textView4"
android:layout_toEndOf="@+id/textView4"
android:background="@drawable/edittext_style"
android:layout_weight="3"
android:hint="Type your grade here" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Programming"
android:id="@+id/textView5"
android:layout_below="@+id/txtProg"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_weight="1" />
<EditText
168
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtProg"
android:layout_alignTop="@+id/textView4"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignLeft="@+id/txtEng"
android:layout_alignStart="@+id/txtEng"
android:background="@drawable/edittext_style"
android:layout_weight="3"
android:hint="Type your grade here" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="15dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Filipino"
android:id="@+id/textView6"
android:layout_below="@+id/txtProg"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_weight="1" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtFil"
android:layout_alignTop="@+id/textView5"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toRightOf="@+id/textView3"
android:layout_toEndOf="@+id/textView3"
android:background="@drawable/edittext_style"
android:layout_weight="3"
android:hint="Type your grade here" />
</TableRow>
</TableLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calculate Grade"
android:id="@+id/btnCalc"
android:layout_below="@+id/txtFil"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/txtFil"
android:layout_marginTop="30dp"
android:layout_alignEnd="@+id/txtFil"
android:background="@drawable/button_style"
android:layout_marginBottom="5dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="RESET"
android:id="@+id/btnRest"
android:background="@drawable/button_style" /
>
</LinearLayout>
169
D. Activity Class Code
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import
android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import
android.widget.Button;
import
android.widget.EditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sum = Float.parseFloat(etEng.getText().toString()) +
Float.parseFloat(etSci.getText().toString()) +
Float.parseFloat(etMath.getText().toString()) +
Float.parseFloat(etProg.getText().toString()) +
Float.parseFloat(etFil.getText().toString());
ave = sum / 5;
170
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
}
}).create();
alert.show()
;
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
etEng.setText("");
etSci.setText("");
etMath.setText("");
etProg.setText("");
etFil.setText("");
etName.setText("");
}
});
}
}
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
171
ListView and Simple Adapters
Android ListView is a view which groups several items and display them in vertical scrollable list. The list
items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or
database.
An adapter actually bridges between UI components and the data source that fill data into UI Component.
Adapter holds the data and send the data to adapter view, the view can take the data from adapter view and
shows the data on different views like as spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can be populated by binding them to
an Adapter, which retrieves data from an external source and creates a View that represents each data entry.
Android provides several subclasses of Adapter that are useful for retrieving different kinds of data and building
views for an AdapterView ( i.e. ListView or GridView). The common adapters are ArrayAdapter,Base.
172
ListView Attributes
Following are the important attributes specific to GridView.
Attribute Description
android:id This is the ID which uniquely identifies the layout.
android:divider This is drawable or color to draw between list items. .
android:dividerHeight This specifies height of the divider. This could be in px, dp,
sp, in, or mm.
android:entries Specifies the reference to an array resource that will
populate the ListView.
android:footerDividersEnabled When set to false, the ListView will not draw the divider
before each footer view. The default value is true.
android:headerDividersEnabled When set to false, the ListView will not draw the divider
after each header view. The default value is true.
ArrayAdapter
You can use this adapter when your data source is an array. By default, ArrayAdapter creates a view for
each array item by calling toString() on each item and placing the contents in a TextView. Consider you have an
array of strings you want to display in a ListView, initialize a new ArrayAdapter using a constructor to specify the
layout for each string and the string array.
Once you have array adapter created, then simply call setAdapter() on your ListView object as follows:
173
You will define your list view under res/layout directory in an XML file. For our example we are going to
using activity_main.xml file. Following is the example which will take you through simple steps to show how to
create your own Android application using ListView. Follow the following steps to modify the Android application
we created in Hello World Example.
Step Description
1 You will use Android Studio IDE to create an Android application and name it
as ListDisplay under a package com.example.ListDisplay as explained in the Hello World
Example chapter.
2 Modify the default content of res/layout/activity_main.xml file to include ListView content
with the self explanatory attributes.
3 No need to change string.xml, Android studio takes care of default string constants.
4 Create a Text View file res/layout/activity_listview.xml. This file will have setting to display
all the list items. So you can customize its fonts, padding, color etc. using this file.
5 Run the application to launch Android emulator and verify the result of the changes done in
the application.
174
Following will be the content of res/layout/activity_main.xml file.
Following will be the content of res/layout/activity_listview.xml file and run the app.
175
Laboratory Exercise 12
Problem Statement
Create an app that can register a student information with student number, full name and year level. All
registered student will be display using a simple ListView. Use spinner to show the year level. When the button
taps it will display the new students and update contents in the ListView. Follow the design layout below.
Requirements:
Composed of one activity named “MainActivity”
Use Spinner to display the list of Year Level in a dropdown.
Use button to trigger when adding a new student in the list.
Follow the string format of the student information display in the ListView.
Legend:
A – This is the layout design for the Main Activity where all the registered students show in the ListView.
B – When the user taps the spinner it will display all the year levels in a dropdown lists.
C – When the user taps the button “Add to the list”, the student information will display in the ListView. The
format is Student #, next line is student name and next is the year level selected.
176
Solution (Code Snippet)
A. Create a new project using Android Studio and see the project structure below for your guide.
B. XML Layout Design Code – The spinner and button is arranged using the TableLayout. See the
component tree for your guide.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student Registration"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="20dp"
android:gravity="center_horizontal"
177
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content
" android:inputType="number"
android:ems="10"
android:id="@+id/etxtStudNo"
android:layout_below="@+id/textVie
w"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="tru
e" android:layout_marginTop="20dp"
android:layout_alignParentRight="tru
e"
android:layout_alignParentEnd="true
"
android:background="@android:drawable/
editbox_background_normal" android:hint="Student no." />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/etxtName"
android:layout_below="@+id/etxtStudNo"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/etxtStudNo"
android:layout_alignEnd="@+id/etxtStudNo"
android:background="@android:drawable/
editbox_background_normal" android:hint="Full name" />
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/etxtName"
android:layout_alignRight="@+id/etxtNam
e"
android:layout_alignEnd="@+id/etxtName
" android:id="@+id/tableLayout">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_vertical">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/spinyrlvl"
android:layout_weight="2"
android:background="@android:drawable/editbox_background_normal"
android:spinnerMode="dropdown" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to the List"
android:id="@+id/btnAdd"
android:layout_weight="1" />
</TableRow>
</TableLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listViewStud"
178
C. Activity Class Code
package com.chady.chadmac.comp3labexercise12;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import
android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
List<String> studList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAddStud.setOnClickListener(new
View.OnClickListener() { @Override
public void onClick(View v) {
if (spinYearLvl.getSelectedItemPosition() == 0) {
Toast.makeText(getApplicationContext(), "Please select your year level!",
Toast.LENGTH_LONG).show();
} else {
studList.add(strStud);
179
txtStudNo.setText("");
txtName.setText("");
spinYearLvl.setSelection(0);
}
}
});
}
}
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
180
Custom ArrayAdapters
For real-world commercial mobile applications, the default looks and feel of the Android ListView is not
very attractive. It only renders a simple String in every ListView row using the internal TextView control. For most
applications, you want to create an interface that is more graphically rich and visually pleasing to the user. Luckily,
ListView is very powerful control and with the help of custom item layouts, it can be customized to suit your needs
easily.
ArrayAdapter is a type of Adapter which acts a bridge between UI component and data source that helps
us to fill data in UI component. It expects a Layout with a single TextView and for more customization in grid items
or list items, we use custom adapters.
ArrayAdapter is also an implementation of BaseAdapter so if we want more customization then we
create a custom adapter and extend ArrayAdapter in that.
We override all the functions of BaseAdapter in our custom adapter to give more customization to
ArrayAdapter.
In the above code snippet we see the overrided functions of ArrayAdapter which are used to set the data
in a list, grid or a spinner. From there we mainly used two functions getCount() and getView() .
getCount() Method
The getCount() function returns the total number of items to be displayed in a list. It counts the value from
arraylist size or an array’s length. For example if we have an list of elements in a array list and we have to display
the items in a list view then we can count the total number of elements using the size function and then that
integer value is returned by the function getCount() as shown below.
181
getView(int i, View view, ViewGroup viewGroup) Method
This function is automatically called when the list item view is ready to be displayed or about to be
displayed. In this function we set the layout for list items using LayoutInflater class and then add the data to the
views like ImageView, TextView etc.
Below is the getView function’s example code with explanation included in which we set the layout using
LayoutInflater and then get the view’s id and implement them.
182
Laboratory Exercise 13
Problem Statement
Create an app that display the different avatar icons with image, name of avatar and its description. The
app has also a delete functionality in each row in the ListView. There is also an ‘insert new data” button at the top
of the view and once the button is tap it will add another avatar in the first item in the ListView.
Requirements:
Composed of only one activity named “MainActivity” and the rest are model for Icon and Custom
Adapter.
Download at least 10 avatar icon/images in the browser and add to the Drawable folder. Make sure
that each icon/avatar image have at least 100KB in file size.
The first 9 avatars will automatically load in the ListView and the remaining avatar is used for inserting
new avatar.
Design a Custom ListView layout based in the design given below.
183
Legend:
A – This is the layout design for the Main Activity where it displays all the 9 avatars with title and
description. Each row in the ListView has a delete button for removing item in the list.
B – When the user taps the “Insert New Data” button, new avatar will automatically insert at first row in the
ListView. (e.g. New avatar is Game Controller). When the delete button tap, it will remove a particular item
in the ListView (e.g. Zombie Avatar)
B. Download at least 10 avatar images/icon using browser and paste it to the Drawable folder. Make sure
that the file size of each images should be at least 100KB and the file name should be one word only and
starts with small letter. See the figure below.
184
C. Class of Icon/Avatar – Create a java class for the Icon inside your java package.
@Override
public String toString() { //to describe the current values of instance variable
return "IconClass [drawableID=" + drawableID + ", titleStr=" + titleStr
+ ", descStr=" + descStr + "]";
}
185
Here is the component tree of the layout for your guide.
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="80dp"
android:layout_height="80dp"
android:focusable="false"
android:background="@mipmap/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/linearLayout3"
android:orientation="vertical" >
<Button
android:id="@+id/btnDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:text="Delete" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/linearLayout2"
android:layout_marginBottom="16dp"
android:layout_toRightOf="@+id/linearLayout2"
android:orientation="vertical"
android:paddingLeft="10dp" >
<TextView
android:id="@+id/txtTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
186
android:focusable="false"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/txtDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</RelativeLayout>
Open the main activity layout and design the given layout below. See the component tree for your guide.
<ListView
android:id="@+id/listviewData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/btnInsert"
android:clickable="true" >
</ListView>
</RelativeLayout>
187
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
Context contextAct;
private ArrayList<IconClass> iconList;
int layoutResID; //layout for custom listview
@Override
public void remove(IconClass object) {
// TODO Auto-generated method stub
super.remove(object);
iconList.remove(object);
}
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)
contextAct.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(layoutResID, null);
188
holder.btndelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button btnTag = (Button) v;
IconClass iconObj = (IconClass) btnTag.getTag();
remove(iconObj);
notifyDataSetChanged();
}
});
}else{
holder = (ViewHolder) view.getTag();
}
return view;
}
}
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import
android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import
android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
{ Button btnAdd;
ListView listview;
IconDataAdapter
iconAdapter; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
189
obj4.setDescStr("cartoon ironman avatar");
obj4.setDrawableID(R.drawable.ava4);
iconDlist.add(obj4);
listview.setOnItemClickListener(new ListView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
IconClass iconObj = (IconClass) parent.getItemAtPosition(position);
// Toast.makeText(getApplicationContext(), "Selected: " + iconObj.getTitleStr(),
Toast.LENGTH_LONG).show();
}
}).create();
alert.show();
}
});
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
190
}
});
}
}
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
191
Case Study: Meal Oder App
Problem Statement
Your task is to create an app for accepting meal orders from customer and register it by tapping the “Add
to cart” button. There are three choices of meal and can be selected by tapping the button. It displays the actual
image of every meal and its description with price. Every order should indicate the number of quantity and add on
for soup. After ordering, list of orders can be view with computation of total amount. See the table below for the list
of meals with their description.
App Specification
Composed of 2 Activity Class for Meal Choices and Order Summary
Use Custom ListView for design layout displaying the order summary.
Use Java array for saving the orders of the customer. This app is only for one transaction only.
Download image from the browser for three meals. Make sure that your image should be up to 500KB file
size so that we can minimize the Exception in loading the image in the app while testing and running.
Requirements
Use buttons for different choices of menu. It will automatically change the image of meal once the button
is tap.
Use Seekbar widget for getting the percentage of saltiness and spiciness of the food.
Use ToggleButton for adding soup for add on per order.
Use AlertDialog for giving information to user about their order transaction.
Use Custom ListView for displaying summary of order.
Design the layout same as the given below.
192
Design Layout
Legend
A – This is the layout design for Main Activity that shows the different choices of meal by tapping the button. There
are three meals available namely Meal A, Meal B and Meal C. Use TextView for displaying the information of
every meal. The Seek bar is used for changing the saltiness and spiciness of the order.
B – When the button “Add to Cart” is tap by the user the AlertDialog will pop-up that informs that the order is
successfully added to the cart.
C – When the button “Add to Cart: is tap without changing the number of quantity, the AlertDialog will pop-up
informing the user for error in quantity.
D – When the order has been added in the cart with at least one order, the order summary will be open once the
button “View Order” is tap. If there is no order registered in the cart display an AlertDialog for Order Error. It will
show the total computation of price at the button of the view. Total Amount should be formatted with at least two
decimal places in the amount.
E – When the user cancel a specific order in the summary lists by tapping the button delete, it will remove the
order in the lists and update the total amount of the order.
193