Unit 5

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 51

MODULE V

Android Introduction
Android is used by most of the mobile users and is a trending topic of modern
technology. It is an open source area of development and is a Linux based OS which acts as
middleware and a key mobile application. This OS is designed to use in modern smartphones,
e-book readers, set-top boxes, tablets, and televisions as well. Open Handset Alliance created
it. In this tutorial, you will learn the basics of Android, and what are its features and categories
of applications developed for Android.

What is Android?
Android is an open source software package that was developed primarily to improve the
mobile user experience and has now become the best-selling operating system for mobile
devices. Android is now a part of Google and the Open Handset Alliance, and the current
version of the Android operating system is Oreo (version 8.0), which was released in August
2017.

Features of Android:
Android is filled with a lot of features which makes it popular in the world. These are:

● Android is a customizable operating system, and therefore users can customize it in their
way.

● It has an opening screen, quick notification option, stylish yet straightforward UI, etc.
● It is an open source application.
● A diverse range of applications can be chosen to install and use from the Android Play
Store.
● It supports Touch-based keyboards.
● It has a Customized Home screen.
● It provides custom ROMs.
● Widgets for better UX
MODULE V

Why we use Android?


● Android provides an extensive developer's community support.
● It uses the core Java language for developing applications.
● It also provides high marketing.
● Application development cost is less.
● Good storage and uses a lightweight relational database, SQLite
● It provides good security.

The Android Platform:

Android is an open source, Linux-based software stack created for a wide array of devices
and form factors. Figure 1 shows the major components of the Android platform.

Linux kernel

The foundation of the Android platform is the Linux kernel. For example, the Android Runtime
(ART) relies on the Linux kernel for underlying functionalities such as threading and low-level
memory management.

Using a Linux kernel lets Android take advantage of key security features and lets device
manufacturers develop hardware drivers for a well-known kernel.

Hardware abstraction layer (HAL)


MODULE V

The hardware abstraction layer (HAL) provides standard interfaces that expose device hardware
capabilities to the higher-level Java API framework. The HAL consists of multiple library modules,
each of which implements an interface for a specific type of hardware component, such as
the camera or Bluetooth module. When a framework API makes a call to access device hardware, the
Android system loads the library module for that hardware component.

Android runtime

For devices running Android version 5.0 (API level 21) or higher, each app runs in its own process
and with its own instance of the Android Runtime (ART). ART is written to run multiple virtual
machines on low-memory devices by executing Dalvik Executable format (DEX) files, a bytecode
format designed specifically for Android that's optimized for a minimal memory footprint. Build
tools, such as d8, compile Java sources into DEX bytecode, which can run on the Android platform.

Some of the major features of ART include the following:

 Ahead-of-time (AOT) and just-in-time (JIT) compilation


 Optimized garbage collection (GC)
 On Android 9 (API level 28) and higher, conversion of an app package's DEX files to more compact
machine code
 Better debugging support, including a dedicated sampling profiler, detailed diagnostic exceptions and
crash reporting, and the ability to set watchpoints to monitor specific fields

Prior to Android version 5.0 (API level 21), Dalvik was the Android runtime. If your app runs well
on ART, then it can work on Dalvik as well, but the reverse might not be true.

Android also includes a set of core runtime libraries that provide most of the functionality of the Java
programming language, including some Java 8 language features, that the Java API framework uses.

Native C/C++ libraries

Many core Android system components and services, such as ART and HAL, are built from native
code that requires native libraries written in C and C++. The Android platform provides Java
framework APIs to expose the functionality of some of these native libraries to apps. For example,
you can access OpenGL ES through the Android framework’s Java OpenGL API to add support for
drawing and manipulating 2D and 3D graphics in your app.

If you are developing an app that requires C or C++ code, you can use the Android NDK to access
some of these native platform libraries directly from your native code.

Java API framework

The entire feature-set of the Android OS is available to you through APIs written in the Java
language. These APIs form the building blocks you need to create Android apps by simplifying the
reuse of core, modular system components and services, which include the following:
MODULE V

 A rich and extensible view system you can use to build an app’s UI, including lists, grids, text boxes,
buttons, and even an embeddable web browser
 A resource manager, providing access to non-code resources such as localized strings, graphics, and
layout files
 A notification manager that enables all apps to display custom alerts in the status bar
 An activity manager that manages the lifecycle of apps and provides a common navigation back stack
 Content providers that enable apps to access data from other apps, such as the Contacts app, or to
share their own data

Developers have full access to the same framework APIs that Android system apps use.

System apps

Android comes with a set of core apps for email, SMS messaging, calendars, internet browsing,
contacts, and more. Apps included with the platform have no special status among the apps the user
chooses to install. So, a third-party app can become the user's default web browser, SMS messenger,
or even the default keyboard. Some exceptions apply, such as the system's Settings app.

The system apps function both as apps for users and to provide key capabilities that developers can
access from their own app. For example, if you want your app to deliver SMS messages, you don't
need to build that functionality yourself. You can instead invoke whichever SMS app is already
installed to deliver a message to the recipient you specify.

Android SDK:
Android SDK stands for Android Software Development Kit which is developed by
Google for Android Platform. With the help of Android SDK, we can create android Apps easily.

About Android SDK


Android SDK is a collection of libraries and Software Development tools that are essential for
Developing Android Applications. Whenever Google releases a new version or update of Android
Software, a corresponding SDK also releases with it. In the updated or new version of SDK, some
more features are included which are not present in the previous version. Android SDK consists of
some tools which are very essential for the development of Android Application. These tools
provide a smooth flow of the development process from developing and debugging. Android SDK
is compatible with all operating systems such as Windows, Linux, macOS, etc.
MODULE V

Components of Android SDK


Android SDK Components play a major role in the Development of Android applications. Below
are the important components:
1. Android SDK Tools
Android SDK tool is an important component of Android SDK. It consists of a complete set of
development and debugging tools. Below are the SDK developer tools:
 Android SDK Build tool.
 Android Emulator.
 Android SDK Platform-tools.
 Android SDK Tools.
These are shown below :

2. Android SDK Build-Tools


Android SDK build tools are used for building actual binaries of Android App. The main functions
of Android SDK Build tools are built, debug, run and test Android applications. The latest version
of the Android SDK Build tool is 30.0.3. While downloading or updating Android in our System,
one must ensure that its latest version is download in SDK Components.
3. Android Emulator
An Android Emulator is a device that simulates an Android device on your system. Suppose we
want to run our android application that we code. One option is that we will run this on our
MODULE V

Android Mobile by Enabling USB Debugging on our mobile. Another option is using Android
Emulator. In Android Emulator the virtual android device is shown on our system on which we run
the Android application that we code.
Thus, it simply means that without needing any physical device Android SDK component
“Android Emulator” provides a virtual device on the System where we run our Application. The
emulator’s come with the configuration for Various android phones, tablets, Wear OS, and Android
TV devices.

In Android Virtual Emulator all functions that are feasible on real Android mobile is works on
virtual Device like:
 phone calls, text messages.
 stimulate different network speeds.
 specify the location of a device
 access on google play store and lot’s more.
But there is one disadvantage of this emulator is that. It is very slow when System’s PC has less
RAM. It works fine when a maximum GB of RAM is present on our device.
4. Android SDK Platform-tools
Android SDK Platform-tools is helpful when we are working on Project and they will show the
error messages at the same time. It is specifically used for testing. It includes:
 Android Debug Bridge (ADB), is a command-line tool that helps to communicate with the
device. It allows us to perform an action such as Installing App and Debugging App etc.
 Fastboot allows you to flash a device with a new system image.
 Systrace tools help to collect and inspect timing information. It is very crucial for App
Debugging.
5. Android SDK Tools
Android SDK tool is a component of SDK tool. It consists of a set of tools which and other
Utilities which are crucial for the development of Android Application. It contains the complete set
of Debugging and Development tools for android.
6. SDK Platforms
For Each Android Software, one SDK platform is available as shown below:

Like in this Android 11.0(R) is installed.


These are numbered according to the android version. The new version of the SDK platform has
more features and more compatible but the old version is less compatible with fewer features. Like
MODULE V

in Android 11.0(R) have more compatible and have more feature but the below versions like
Android 10.0(Q), Android4.4(KitKat) have less feature and is less compatible.
7. SDK Update Sites
In SDK Update Sites, some sites are embedded in it which will check for Android SDK Updates
Tools. In this, one must ensure we don’t unclick the button below because these are checked by
default which will check for updates if we will unclick it then it doesn’t check updates for those.

Android Application Development can be done using Android Studio as well as Eclipse IDE. We
can create android applications in Eclipse IDE using the ADT plugin. Eclipse is preferred for
creating small android applications. Eclipse IDE is an open-source software used by developers, it
contains a variety of plugins to develop software in different programming languages. We will be
using Eclipse IDE to set up Android App Development. First, we need to install Eclipse IDE, and
then we will be setting it up for Android App Development.
Steps to Install Eclipse IDE
1. To install Eclipse IDE, click on Download Eclipse
2. Download JDK (Java Development Kit) and Android Studio as well.
3. In File Explorer, go to Downloads – “Eclipse IDE” will be downloaded.
4. Open Eclipse IDE, choose Eclipse IDE for Java Developers and Install.
5. Eclipse IDE environment is ready, now it’s time to set up Android Development.
Steps to Setup Eclipse IDE for Android App Development
Step 1: Open Eclipse IDE.
Step 2: Select Help, Click on “Install New Software”
MODULE V

Step 3: Type “https://dl-ssl.google.com/android/eclipse/” in the “Work With” section and click


on Add. Further, a new Dialog box will appear, type Name – ADT Repository and Click on Add.

Step 4: You can see Developer Tools under Name – tick the box, then click Next. A dialog box
will appear, click on Next and then click on Finish. After that, Installation will begin.

The installation will take some time:


MODULE V

Step 5: After the installation is completed, Eclipse will be restarted. After the restart, a dialog box
will appear for setting up the Preferences. Click on Open Preferences then Click on Proceed. If the
dialog box does not appear then go to Eclipse -> Window -> Preferences.

Step 6: Browse the SDK Location of Android (C:\Program Files\Android\android-sdk) and Click
Apply.
Note 1: SDK Path is also present in Android Studio -> Tools -> SDK Manager -> Copy the
Android SDK Location path and paste it here.
MODULE V

Note 2: If in case after Step 6, if you are facing this issue “Could not find folder ‘tools’ inside SDK”
please refer to this article How to fix Could not find folder ‘tools’ inside SDK in Android?
Step 7: Click on Install new SDK then Next. Another dialog box will appear, Accept all three
packages and Click on Install.

After installation of packages, SDK Manager will appear for API Level Build Tools and System
Images installation. Click on Install.
Step 8: After installation is completed, Go to Eclipse then Select Window then Click on Android
Virtual Device Manager. A dialog box will appear, Select existing AVD and Click on Edit.

Fill in all the details as per the below image. Click OK.
MODULE V

Step 9: To create an android application, Select File -> New -> Other, and then the below dialog
box will appear Select Android -> Android Application Project then Click on Next. Follow the
steps and then click on Finish.

Step 10: Eclipse IDE setup is completed for Android Application Development.
MODULE V

Create a New Android Project

The first step is to create a new Android project. Open your Eclipse installation, and let’s get started!

1) Open the File menu. Select New followed by Project.

2) In the New Project wizard, select Android followed by Android Project. Click Next.

3) Enter a name for your project (in this example, we’ll use AndroidApp) and select the location
where your project will be stored. Click Next.

4) Enter a build target — this must not be greater than the target used by the Android Virtual Device
(AVD), which is used to configure your Android Emulator. Click Next.
MODULE V

5) On the Application Info page, enter the following information:

 Package name
 Create Activity
 Minimum SDK
After you have entered this information, click Finish.

You have just created your first Android project.

Create Your Android App

You are now ready to create a basic Android app.

In Eclipse’s Package Explorer, open the res folder, followed by layout andmain.xml.
MODULE V

The big advantage of declaring your UI in XML is that it helps to keep the presentation of your app
separate from the code that controls your app’s behavior. For this reason, we will be solely working
with XML in this tutorial. At this point, your XML code should read like this:

{?xml version="1.0" encoding="utf-8"?}

{LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" }

{TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” /}

{/LinearLayout}

But how will this look on an actual Android device? The Android SDK includes a mobile device
emulator, which allows you to quickly and easily test your app without ever leaving the development
environment. To see your app in action, make sure the AndroidApp folder is selected in Eclipse’s
Package Explorer, and select Run from the menu.
MODULE V

After the Android Emulator has finished loading, you can see your basic app in action.

Create Some Buttons in Android

Obviously, we still have some way to go before your app is ready for the Android Market! But let’s
start by adding a basic button. Adding a button that says Ok is simply a matter of adding a code
snippet to themain.xml folder:

{Button

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Ok" /}
The XML code should now look like this:
MODULE V

Check this in the Android Emulator.

Tip: To Change The Text Displayed On The Button, You Simply Need To Edit One
Line: Android:Text="Ok" /}.
So, if you wanted your button to say Cancel you would enter:

android:text="Cancel" /}
With Android, the buttons you can add are practically endless, but another popular button is the radio
button. Again, thanks to Eclipse and the ADT project, this is simply a matter of writing a few lines of
code:

{RadioButton

android:id="@+id/radioButton1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Yes" /}
The entire code should now look like this:
MODULE V

Run this code in the Android Emulator and you will see a radio button has successfully been added.

Tip: Again, Changing The Text Displayed On This Button Is Simply A Matter Of Altering One
Line: Android:Text="Yes" />.

Creating a Clock Widget in Android

Now you’ve got the hang of creating some buttons, it’s time to try something more complicated.

In themain.xml file, delete the code for the two buttons you have just created (or alternatively, create
a new Android project). In this part of the tutorial, we’re going to create an analog clock and then
move it around the screen.

The XML for a basic analog clock is:

{AnalogClock
MODULE V

android:id="@+id/analogClock1"

android:layout_width="wrap_content"

android:layout_height="wrap_content" /}

{/LinearLayout}
Add this to your existing code:

Check this is the Android Emulator. You should now see a working analog clock!

Android Manifest File: Examples, relevance and location

Every Android project has an AndroidManifest.xml file, which is kept in the root directory of the
project hierarchy. The manifest file is a crucial component of our program since it specifies the
metadata, needs, and application
structure. WorkspaceName>/temp/AppName>/build/luaandroid/dist is where you may find the file.
The manifest file gives the Android operating system and Google Play Store crucial information
about your app. The permissions that an app needs to have in order to access data from other
applications are declared within the Android manifest file.

What is an Android application manifest file?

Information about an Android application is contained in the Android App Manifest. At the base of
the source set, there is a single AndroidManifest.xml file for each application. Android App
Manifests are used by the Android operating system and digital distribution platforms (like Google
Play) to locate details about an application, including its name, entry point, support for hardware
features, Android version, and permissions. See the Android Developer documentation on Android
App Manifests for further details about the Android App Manifest file and a list of the parameters
that it configures.

The program metadata, which includes the icon, version number, themes, etc., is included in the
manifest file. Additional top-level nodes can also provide any necessary permissions, unit tests, and
hardware, screen, or platform requirements. A root manifest tag with the project's package as its
package attribute makes up the manifest. Additionally, an xmls:android attribute that provides a
number of system attributes utilized inside the file should be included. The versionCode property is
internally used to specify the current application version as a number that automatically increases
MODULE V

with each repetition of the version that has to be updated. A public version that will be shown to
users is also specified using the versionName parameter.

Here are some of the most important points:

 It specifies the application's Java package name. The package name acts as the application's
special identification.
 It outlines the elements that make up the application, including its functions, services,
broadcast receivers, and content suppliers. Each component's implementation classes are
shown, along with its capabilities (for example, which Intent messages they can handle). The
Android system may learn more about the components and the circumstances in which they
might be launched thanks to these declarations. More of these will be further discussed in this
article.

Structure of the manifest file

The structure of the file usually takes the form of a code-like instruction and looks usually like this:

<manifest>

<application>

<activity

android:name="com.example.applicationname.MainActivity">

</activity>

</application>

</manifest>

The following data is contained in the Manifest file:

 The name of the application's package, often known as the namespace of the code. As the
project is being built, this information is utilized to locate the code.
 The component that consists of all the actions, services, recipients, and content providers is
another.
 The permissions that the application needs in order to access the system's and other apps'
protected areas.
 Which devices can download the app from Google Play depends on the functionality that the
app needs. Both hardware and software features are included in these features.
 Additionally, it contains information about the program metadata, such as the icon, version,
themes, etc.

Furthermore, here are some other things it does:

 It selects the processes that will host the various application components.
MODULE V

 It specifies which rights are necessary for the application to communicate with other
programs and access restricted areas of the API.
 It includes a list of the instrumentation classes, which offer profiling and other data while the
program is operating. These declarations are deleted from the manifest before the application
is released and are only present there while the application is being built and tested.
 It specifies the Android API level that the application must have at a minimum.
 It also specifies which libraries that the program must be linked against

Typically, the android manifest.xml file looks like this:

<?xml version="1.0" encoding="utf-8"?>

<manifest

xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.myfirstapplication">

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<activity

android:name=".MainActivity">

<intent-filter>

<action

android:name="android.intent.action.MAIN" />

<category
MODULE V

android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<meta-data

android:name="preloaded_fonts"

android:resource="@array/preloaded_fonts" />

</application>

</manifest>

How to edit Android manifest file

To make modifications to your file, follow these steps;

Update the AndroidManifest.xml file to include a Detail Activity class. When you test the program,
this declaration allows the application to launch a customer detail screen where you may make
adjustments.

1. Double-click the AndroidManifest.xml file in Package Explorer.


2. The AndroidManifest.xml tab should be selected.
3. Fill up the AndroidManifest.xml file with these settings. To copy and paste the
full <activity> element, utilize the AndroidManifest.xml file contained in the ZIP archive:

<activity

android:name=".DetailActivity"

android:label="@string/app_name">

<intent-filter>

<action

android:name="android.intent.action.MAIN" />

<category

android:name="android.intent.category.LAUNCHER" />

</intent-filter>
MODULE V

</activity>

1. choose File > Save

Element tags of manifest file

A manifest file contains the nodes that specify the test classes, requirements, security settings, and
application components. Among the most common manifest sub-node tags are:

<manifest>

It is this element's root component. It is made up of a package attribute package that specifies the
name of the activity's package.

<application>

The namespace declaration is contained in the subclass of the manifest file. It has several
characteristics. These properties identify the components of the application, and they comprise:

 icon
 allowBackup
 label
 theme

<activity>

Activity is a component of each application. The statement of the activity that is required in the
manifest file is included there. Additionally, it contains characteristics like a name, label, theme, etc.

<intent-filter>

It specifies the kind of intent that the Android components can respond to and is a component of the
activity.

<action>

This component gives the intent filter an action. At least one active element is required for each
intent filter.

<category>

The category name is added by this element to an intent filter.

<service>
MODULE V

The operations offered by libraries or APIs are included in this element.

How to define the app components?

The fundamental building blocks of an Android app are called app components. In the manifest file,
you must specify a corresponding XML element for each app component you build in your project.

Each element serves as a point of entry for the system or a user to access your program. Some
elements rely on other elements.

Four main categories of app components exist:

 <activity> for each subclass of Activity.


 <service> for each subclass of Service.
 <receiver> for each subclass of BroadcastReceiver.
 <provider> for each subclass of ContentProvider.

Each type has a unique lifetime that outlines how the component is formed and destroyed, in addition
to serving a specific purpose. The four categories of app components are described in the sections
that follow.

How to set manifest file permissions in Android?

To access other Android applications or the Internet, an app must first get certain permissions. The
manifest file, manifest.xml, is automatically created when our program is being built. We have
specified the permissions in this manifest file. If no permission is given by us, a few permissions are
automatically applied.

The users have the option of accepting or rejecting the permissions listed in the manifest file. The
protected features can be used by the program after the user gives it permission to do so. The user
must provide permission for the app to access the protected features; otherwise, it will not.

By default, the following permissions are included and are turned to TRUE:

 INTERNET
 ACCESS_NETWORK_STATE
 READ_PHONE_STATE
MODULE V

Your clock will automatically appear in the top left hand corner, but we can change this by adding a
few lines of code and specifying whether the clock should appear centered, in the right hand corner,
or at the bottom of the screen. The code you should add/modify, has been highlighted in the
screenshot below:

Run this in the Android Emulator.

Changing the location of the clock is a similar process to altering the text for your buttons; simply
modify the following line:

android:gravity="center" android_layout_gravity="center"}
For example, if you wanted your clock to be displayed in the right hand corner, the command would
be:
MODULE V

android:gravity="right" android_layout_gravity="right"}

User Interface Elements


When designing your interface, try to be consistent and predictable in your choice of interface
elements. Whether they are aware of it or not, users have become familiar with elements acting in a
certain way, so choosing to adopt those elements when appropriate will help with task completion,
efficiency, and satisfaction.

Interface elements include but are not limited to:

 Input Controls: checkboxes, radio buttons, dropdown lists, list boxes, buttons, toggles, text
fields, date field
 Navigational Components: breadcrumb, slider, search field, pagination, slider, tags, icons
 Informational Components: tooltips, icons, progress bar, notifications, message boxes, modal
windows
 Containers: accordion
Input Controls

Element Description Examples

Checkboxes Checkboxes allow the user to


select one or more options from
a set. It is usually best to
present checkboxes in a vertical
list. More than one column is
acceptable as well if the list is
long enough that it might
require scrolling or if
comparison of terms might be
necessary.

Radio Radio buttons are used to allow


buttons users to select one item at a
time.
MODULE V

Element Description Examples

Dropdown Dropdown lists allow users to


lists select one item at a time,
similarly to radio buttons, but
are more compact allowing you
to save space. Consider adding
text to the field, such as ‘Select
one’ to help the user recognize
the necessary action.

List boxes List boxes, like checkboxes,


allow users to select a multiple
items at a time,but are more
compact and can support a
longer list of options if needed.

Buttons A button indicates an action


upon touch and is typically
labeled using text, an icon, or
both.

Dropdown The dropdown button consists


Button of a button that when clicked
displays a drop-down list of
mutually exclusive items.
MODULE V

Element Description Examples

Toggles A toggle button allows the user


to change a setting between two
states. They are most effective
when the on/off states are
visually distinct.

Text fields Text fields allow users to enter


text. It can allow either a single
line or multiple lines of text.

Date and A date picker allows users to


time pickers select a date and/or time. By
using the picker, the
information is consistently
formatted and input into the
system.

Navigational Components
MODULE V

Element Description Examples

Search Field A search box allows


users to enter a
keyword or phrase
(query) and submit
it to search the
index with the
intention of getting
back the most
relevant results.
Typically search
fields are single-line
text boxes and are
often accompanied
by a search button.

Breadcrum Breadcrumbs allow


b users to identify
their current
location within the
system by providing
a clickable trail of
proceeding pages to
navigate by.

Pagination Pagination divides


content up between
pages, and allows
users to skip
between pages or go
in order through the
content.
MODULE V

Element Description Examples

Tags Tags allow users to


find content in the
same category.
Some tagging
systems also allow
users to apply their
own tags to content
by entering them
into the system.

Sliders A slider, also


known as a track
bar, allows users to
set or adjust a
value. When the
user changes the
value, it does not
change the format
of the interface or
other info on the
screen.
MODULE V

Element Description Examples

Icons An icon is a
simplified image
serving as an
intuitive symbol
that is used to help
users to navigate the
system. Typically,
icons are
hyperlinked.

Image Image carousels


Carousel allow users to
browse through a
set of items and
make a selection of
one if they so
choose. Typically,
the images are
hyperlinked.

Android Layout is used to define the user interface that holds the UI controls or widgets that will
appear on the screen of an android application or activity screen. Generally, every application is a
combination of View and ViewGroup. As we know, an android application contains a large number
of activities and we can say each activity is one page of the application. So, each activity contains
multiple user interface components and those components are the instances of the View and
ViewGroup. All the elements in a layout are built using a hierarchy
of View and ViewGroup objects.

View

A View is defined as the user interface which is used to create interactive UI components such
as TextView, ImageView, EditText, RadioButton, etc., and is responsible for event handling and
drawing. They are Generally Called Widgets.
MODULE V

View

A ViewGroup act as a base class for layouts and layouts parameters that hold other Views or
ViewGroups and to define the layout properties. They are Generally Called layouts.

ViewGroup

The Android framework will allow us to use UI elements or widgets in two ways:
 Use UI elements in the XML file
 Create elements in the Kotlin file dynamically

Types of Android Layout

 Android Linear Layout: LinearLayout is a ViewGroup subclass, used to provide child View
elements one by one either in a particular direction either horizontally or vertically based on the
orientation property.
MODULE V

 Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify the


position of child View elements relative to each other like (A to the right of B) or relative to the
parent (fix to the top of the parent).
 Android Constraint Layout: ConstraintLayout is a ViewGroup subclass, used to specify the
position of layout constraints for every child View relative to other views present. A
ConstraintLayout is similar to a RelativeLayout, but having more power.
 Android Frame Layout: FrameLayout is a ViewGroup subclass, used to specify the position
of View elements it contains on the top of each other to display only a single View inside the
FrameLayout.
 Android Table Layout: TableLayout is a ViewGroup subclass, used to display the child View
elements in rows and columns.
 Android Web View: WebView is a browser that is used to display the web pages in our
activity layout.
 Android ListView: ListView is a ViewGroup, used to display scrollable lists of items in a
single column.
 Android Grid View: GridView is a ViewGroup that is used to display a scrollable list of items
in a grid view of rows and columns
Drawing and Working with Animation:
With Android, we can display images such as PNG and JPG graphics, as well as
text and primitive shapes to the screen. We can paint these items with various colors,
styles, or gradients and modify them using standard image transforms. We can even
animate objects to give the illusion of motion.

Canvas and Paint:

The Canvas class holds the "draw" calls. To draw something, you need 4 basic
components:
1. A Bitmap to hold the pixels,
2. A Canvas to host the draw calls (writing into the bitmap),
3. A drawing primitive (e.g. Rect, Path, text, Bitmap), and
4. A paint (to describe the colors and styles for the drawing).

The android.graphics framework divides drawing into two areas:


What to draw, handled by Canvas
How to draw, handled by Paint.

For instance, Canvas provides a method to draw a line, while Paint provides
MODULE V

methods to define that line's color. Canvas has a method to draw a rectangle, while
Paint defines whether to fill that rectangle with a color or leave it empty. Simply put,
Canvas defines shapes that you can draw on the screen, while Paint defines the
color, style, font, and so forth of each shape you draw.
MODULE V

So, before you draw anything, you need to create one or more Paint objects. The
PieChart example does this in a method called init, which is called from the
constructor from Java.

private void init() {


textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(textColor);
if (textHeight == 0) {
textHeight = textPaint.getTextSize();
} else {
textPaint.setTextSize(textHeight);
}

piePaint = new Paint(Paint.ANTI_ALIAS_FLAG);


piePaint.setStyle(Paint.Style.FILL);
piePaint.setTextSize(textHeight);

shadowPaint = new Paint(0);


shadowPaint.setColor(0xff101010);
shadowPaint.setMaskFilter(new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL));

...

Creating objects ahead of time is an important optimization. Views are redrawn very
frequently, and many drawing objects require expensive initialization. Creating
drawing objects within your onDraw() method significantly reduces performance and
can make your UI appear sluggish.

Once you have your object creation and measuring code defined, you can implement
onDraw(). Every view implements onDraw() differently, but there are some common
operations that most views share:

Draw text using drawText(). Specify the typeface by calling setTypeface(), and
the text color by calling setColor().
Draw primitive shapes using drawRect(), drawOval(), and drawArc(). Change
whether the shapes are filled, outlined, or both by calling setStyle().
Draw more complex shapes using the Path class. Define a shape by adding lines and
curves to a Path object, then draw the shape using drawPath(). Just as with primitive
MODULE V

shapes, paths can be outlined, filled, or both, depending on the setStyle().

Define gradient fills by creating LinearGradient objects. Call setShader() to use


your LinearGradient on filled shapes.
Draw bitmaps using drawBitmap().

For example, here's the code that draws PieChart. It uses a mix of text, lines, and
shapes.

protected void onDraw(Canvas canvas) {


super.onDraw(canvas);

// Draw the shadow


canvas.drawOval(shadowBounds, shadowPaint);

// Draw the label text


canvas.drawText(data.get(currentItem).mLabel, textX, textY, textPaint);

// Draw the pie slices


for (int i = 0; i < data.size(); ++i)
{ Item it = data.get(i);
piePaint.setShader(it.shader);
canvas.drawArc(bounds,360 - it.endAngle, it.endAngle - it.startAngle,
true, piePaint);
}
// Draw the pointer
canvas.drawLine(textX, pointerY, pointerX, pointerY, textPaint);
canvas.drawCircle(pointerX, pointerY, pointerSize, mTextPaint);
}

Bitmaps:

You can find lots of goodies for working with graphics such as bitmaps in the
android.graphics package. The core class for bitmaps is android.graphics.Bitmap.
MODULE V

Drawing Bitmap Graphics on a Canvas

You can draw bitmaps onto a valid Canvas, such as within the onDraw() method of a
View, using one of the drawBitmap() methods. For example, the following code loads
a Bitmap resource and draws it on a canvas:

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
...
Bitmap pic = BitmapFactory.decodeResource(getResources(),
R.drawable.bluejay);
canvas.drawBitmap(pic, 0, 0, null);

Scaling Bitmap Graphics

Perhaps you want to scale your graphic to a smaller size. In this case, you can use
the createScaledBitmap() method, like this:

Bitmap sm = Bitmap.createScaledBitmap(pic, 50, 75, false);

You can preserve the aspect ratio of the Bitmap by checking the getWidth() and
getHeight() methods and scaling appropriately.

Shapes:

You can define and draw primitive shapes such as rectangles and ovals using the
ShapeDrawable class in conjunction with a variety of specialized Shape classes.
You can define Paintable drawables as XML resource files, but more often,
especially with more complex shapes, this is done programmatically.

Defining Shape Drawables as XML Resources

In Unit-5, of block-3, we show you how to define primitive


MODULE V

shapes such as rectangles using specially formatted XML files within the
/res/drawable/resource directory.
The following resource file called /res/drawable/green_rect.xml describes a simple,
green rectangle shape drawable:

</shape>

You can then load the shape resource and set it as the Drawable as follows:

ImageView iView = (ImageView)findViewById(R.id.ImageView1);


iView.setImageResource(R.drawable.green_rect);

You should note that many Paint properties can be set via XML as part of the Shape
definition. For example, the following Oval shape is defined with a linear gradient
(red to white) and stroke style information:/>

</shape>

Defining Shape Drawables Programmatically

You can also define this ShapeDrawable instances programmatically. The different
shapes are available as classes within the android.graphics.drawable.shapes package.
For example, you can programmatically define the aforementioned green rectangle as
follows:
MODULE V

import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
...

ShapeDrawable rect = new ShapeDrawable(new RectShape());


rect.getPaint().setColor(Color.GREEN);

You can then set the Drawable for the ImageView directly:

ImageView iView = (ImageView)findViewById(R.id.ImageView1);


iView.setImageDrawable(rect);

Drawing Different Shapes

Some of the different shapes available within the android.graphics.drawable.shapes


package include

Rectangles (and squares)


Rectangles with rounded corners
Ovals (and circles)
Arcs and lines
Other shapes defined as paths

You can create and use these shapes as Drawable resources directly within ImageView
views, or you can find corresponding methods for creating these primitive shapes within
a Canvas.

Drawing Rectangles and Squares

Drawing rectangles and squares (rectangles with equal height/width values) is simply a
matter of creating a ShapeDrawable from a RectShape object. The RectShape object
has no dimensions but is bound by the container object in this case, the ShapeDrawable.
MODULE V

You can set some basic properties of the ShapeDrawable, such as the Paint color
and the default size.

For example, here we create a magenta-colored rectangle that is 100-pixels long


and 2-pixels wide, which looks like a straight, horizontal line. We then set the shape
as the drawable for an ImageView so the shape can be displayed:

import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;

ShapeDrawable rect = new ShapeDrawable(new RectShape());


rect.setIntrinsicHeight(2);
rect.setIntrinsicWidth(100);
rect.getPaint().setColor(Color.MAGENTA);
ImageView iView = (ImageView)findViewById(R.id.ImageView1);
iView.setImageDrawable(rect);

Similarly we can draw other shapes.

Frame by Frame animation:

You can think of frame-by-frame animation as a digital flipbook in which a series of


similar images display on the screen in a sequence, each subtly different from the
last. When you display these images quickly, they give the illusion of movement.
This technique is called frame-by-frame animation and is often used on the Web in
the form of animated GIF images.

Frame-by-frame animation is best used for complicated graphics transformations


that are not easily implemented programmatically.

An object used to create frame-by-frame animations, defined by a series of Drawable


objects, which can be used as a View object's background.
MODULE V
MODULE V

The simplest way to create a frame-by-frame animation is to define the animation in


an XML file, placed in the res/drawable/ folder, and set it as the background to a
View object. Then, call start() to run the animation.

An AnimationDrawable defined in XML consists of a single <animation-list> element


and a series of nested <item> tags. Each item defines a frame of the animation. See the
example below.

spin_animation.xml file in res/drawable/ folder:

<animation-list android:id="@+id/selected" android:oneshot="false">


<item android:drawable="@drawable/wheel0" android:duration="50" />
<item android:drawable="@drawable/wheel1" android:duration="50" />
<item android:drawable="@drawable/wheel2" android:duration="50" />
<item android:drawable="@drawable/wheel3" android:duration="50" />
<item android:drawable="@drawable/wheel4" android:duration="50" />
<item android:drawable="@drawable/wheel5" android:duration="50" />
</animation-list>

Here is the code to load and play this animation.

// Load the ImageView that will host the animation and


// set its background to our AnimationDrawable XML resource.
ImageView img = (ImageView)findViewById(R.id.spinning_wheel_image);
img.setBackgroundResource(R.drawable.spin_animation);

// Get the background, which has been compiled to an AnimationDrawable object.


AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();

// Start the animation (looped playback by default).


frameAnimation.start();
MODULE V

Tweened Animation:

With tweened animation, you can provide a single Drawable resource - it is a Bitmap
graphic, a ShapeDrawable, a TextView, or any other type of View object and the
intermediate frames of the animation are rendered by the system. Android provides
tweening support for several common image transformations, including alpha, rotate,
scale, and translate animations. You can apply tweened animation transformations
to any View, whether it is an ImageView with a Bitmap or shape Drawable, or a
layout such as a TableLayout.

Defining Tweening Transformations

You can define tweening transformations as XML resource files or programmatically.


All tweened animations share some common properties, including when to start, how
long to animate, and whether to return to the starting state upon completion.

Defining Tweened Animations as XML Resources

In Unit-5 of Block-3, we showed you how to store animation sequences as specially


formatted XML files within the /res/anim/ resource directory. For example, the
following resource file called /res/anim/spin.xml describes a simple five-second
rotation:

<rotate android
MODULE V

</set>

andr

</set>

Loading Animations

Loading animations is made simple by using the AnimationUtils helper class.The


following code loads an animation XML resource file called /res/anim/grow.xml and
applies it to an ImageView whose source resource is a green rectangle shape drawable:

import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
...
ImageView iView = (ImageView)findViewById(R.id.ImageView1);
iView.setImageResource(R.drawable.green_rect);
Animation an = AnimationUtils.loadAnimation(this, R.anim.grow);
iView.startAnimation(an);

We can listen for Animation events, including the animation start, end, and repeat
MODULE V

events, by implementing an AnimationListener class, such as the MyListener class


shown here:
class MyListener implements Animation.AnimationListener {
public void onAnimationEnd(Animation animation) {
// Do at end of animation
}
public void onAnimationRepeat(Animation animation) {
// Do each time the animation loops
MODULE V

}
public void onAnimationStart(Animation animation) {
// Do at start of animation
}
}

You can then register your AnimationListener as follows:


an.setAnimationListener(new MyListener());

four types of tweening transformations individually.


These types are:
Transparency changes (Alpha)
Rotations (Rotate)
Scaling (Scale)
Movement (Translate)

Working with Alpha Transparency Transformations

Transparency is controlled using Alpha transformations. Alpha transformations can


be used to fade objects in and out of view or to layer them on the screen.

Alpha values range from 0.0 (fully transparent or invisible) to 1.0 (fully opaque or
visible). Alpha animations involve a starting transparency (fromAlpha) and an ending
transparency (toAlpha).

The following XML resource file excerpt defines a transparency-change animation,


taking five seconds to fade in from fully transparent to fully opaque:
<alpha

andr
</alpha>
Programmatically, you can create this same animation using the AlphaAnimation
MODULE V

class within the android.view.animation package.


MODULE V

Working with Rotating Transformations

You can use rotation operations to spin objects clockwise or counterclockwise


around a

Rotations are defined in terms of degrees. For example, you might want an object to
make one complete clockwise rotation. To do this, you set the fromDegrees property to
0 and the toDegrees property to 360. To rotate the object counterclockwise
instead, you set the toDegrees property to -360.

By default, the object pivots around the (0,0) coordinate, or the top-left corner of the
object. This is great for rotations such as those of
time, you want to pivot from the center of the object; you can do this easily by setting
the pivot point, which can be a fixed coordinate or a percentage.

The following XML resource file excerpt defines a rotation animation, taking five
seconds to make one full clockwise rotation, pivoting from the center of the object:

<rotate

Programmatically, you can create this same animation using the RotateAnimation
class within the android.view.animation package.

Working with Scaling Transformations

You can use scaling operations to stretch objects vertically and horizontally. Scaling
operations are defined as relative scales.Think of the scale value of 1.0 as 100 percent,
or fullsize. To scale to half-size, or 50 percent, set the target scale value of
0.5. You can scale horizontally and vertically on different scales or on the same
scale (to preserve aspect ratio).You need to set four values for proper scaling:
MODULE V

starting scale (fromXScale, fromYScale) and target scale (toXScale, toYScale). Again, you
can use a pivot point to stretch your object from a specific (x,y) coordinate such as the
center or another coordinate.

The following XML resource file excerpt defines a scaling animation, taking five
seconds

<scale

android:

Programmatically, you can create this same animation using the ScaleAnimation
class within the android.view.animation package.

Working with Moving Transformations

You can move objects around using translate operations.Translate operations move an
object from one position on the (x,y) coordinate to another coordinate.

To perform a translate operation, you must specify the change, or delta, in the
coordinates. You can set four values for translations: starting position
(fromXDelta, fromYDelta) and relative target location (toXDelta, toYDelta).

The following XML resource file excerpt defines a translate animation, taking 5
seconds to move an object up (negative) by 100 on the y-axis.We also set the
fillAfter
when the animation finishes:
<translate -
MODULE V
MODULE V

Programmatically, you can create this same animation using the TranslateAnimation class within the
android.view.animation package.
MODULE V

You might also like