0% found this document useful (0 votes)
9 views44 pages

Mad Module - 2

The document provides an overview of Android application components, including Activities, Services, Broadcast Receivers, and Content Providers, detailing their roles and implementations. It also discusses Android API levels, the structure of an Android project, and the importance of the AndroidManifest.xml file in managing application components and permissions. Additionally, it outlines the activity lifecycle and how to declare activities and intent filters within the manifest.

Uploaded by

Samuel Johnpeter
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views44 pages

Mad Module - 2

The document provides an overview of Android application components, including Activities, Services, Broadcast Receivers, and Content Providers, detailing their roles and implementations. It also discusses Android API levels, the structure of an Android project, and the importance of the AndroidManifest.xml file in managing application components and permissions. Additionally, it outlines the activity lifecycle and how to declare activities and intent filters within the manifest.

Uploaded by

Samuel Johnpeter
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MAD Module – II

Understanding Role of Android Application Components:

Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file [Link] that
describes each component of the application and how they interact.

There are following four main components that can be used within an Android application −

1. Activities
2. Services
3. Broadcast Receivers
4. Content Providers
Activities:

An activity represents a single screen with a user interface, in-short Activity performs
actions on the screen. For example, an email application might have one activity that shows
a list of new emails, another activity to compose an email, and another activity for reading
emails. If an application has more than one activity, then one of them should be marked as
the activity that is presented when the application is launched.

An activity is implemented as a subclass of Activity class as follows −

public class MainActivity extends Activity {


}

Services:

A service is a component that runs in the background to perform long-running operations.


For example, a service might play music in the background while the user is in a different
application, or it might fetch data over the network without blocking user interaction with
an activity.

A service is implemented as a subclass of Service class as follows −

public class MyService extends Service {


}

Broadcast Receivers:

Broadcast Receivers simply respond to broadcast messages from other applications or from
the system. For example, applications can also initiate broadcasts to let other applications
know that some data has been downloaded to the device and is available for them to use,
so this is broadcast receiver who will intercept this communication and will initiate
appropriate action.

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each


message is broadcaster as an Intent object.
MAD Module – II

public class MyReceiver extends BroadcastReceiver {


public void onReceive(context,intent){}
}

Content Providers:

A content provider component supplies data from one application to others on request.
Such requests are handled by the methods of the ContentResolver class. The data may be
stored in the file system, the database or somewhere else entirely.

A content provider is implemented as a subclass of ContentProvider class and must


implement a standard set of APIs that enable other applications to perform transactions.

public class MyContentProvider extends ContentProvider {


public void onCreate(){}
}

Android API Levels


There are various API levels in Android OS, and still, new APIs are developed as the
development is going on with new features and functions in Android devices. Every new
Android version introduces a new change that leads to more secure and high-performance
improvements. Introducing a new API level also enhances the user experience of Android
overall.

Application program interface (API) is a code for a programmer that they use in their
applications. This code or (API) allows you to add specific functionalities to your application.
In other words, we can say that APIs are the set of protocols and tools used for building
software applications

From the developer's perspective, an Android API (or API Levels) is an integer value that
uniquely recognizes the framework of API revision.

Platform Version API Level

Android 2.3.3 10

Android 2.3 9

Android 2.2 8

Android 2.1 7

Android 2.0.1 6

Android 2.0 5

Android 1.6 4

Android 1.5 3
MAD Module – II

Android 1.1 2

Android 1.0 1

The android platform offers an API that Android applications use to communicate with the
underlying Android system. Android framework API consists of the followings points:

o It is a core set of packages and classes.


o A collection of XML elements and attributes is declared in a manifest file. It is also used
for accessing resources.
o It also contains the set of permissions the application can request to use device
resources and enforcements included in the system.
How do APIs work?
APIs work by sharing data between applications, systems, and devices. This happens through
a request and response cycle. A user initiates a request for data by interacting with an
application. The request is sent to the API, which retrieves the data and returns it to the user.

To understand this process better, check out how Google Maps works on apps like Ola, Uber,
Zomato, and Swiggy. This app allows you to track the location of your order using the map
feature. Additionally, these apps do not have their own satellites to track your location
through the map.
These apps don’t access Google Maps data directly because Google adds a layer of security
called the Google Map API.

So, when Swiggy wants to retrieve data, it first talks to the Google Maps API instead of
talking to the Google Maps directly. Therefore, an API can be said to be a messenger that
transfers data from one application to another.
MAD Module – II

How to add API (or API levels) in your application:

Suppose you want to add a new API level to your Android application (using Android Studio
Software). In that case, you must navigate to Appearance & Behaviour > System Settings >
and Android SDK. Once you are at the Android SDK screen, checkmark the box next to the
API levels and their features. After that, click on the "OK" button to apply and make the
changes you have done. It will download and install the selected API on the Android Studio
Platform, which you can use in your application.

Android App / Project Folder Structure


To implement android apps, Android Studio is the official IDE (Integrated Development
Environment) which is freely provided by Google for android app development.

Once we setup android development environment using android studio and if we create a
sample application using android studio, our project folder structure will be like as shown
below.
MAD Module – II

The Android project structure on the disk might be differs from the above representation.
To see the actual file structure of the project, select Project from the Project dropdown
instead of Android.

The android app project will contain different types of app modules, source code files, and
resource files. We will explore all the folders and files in the android app.

Java Folder
This folder will contain all the java source code (.java) files which we’ll create during the
application development, including JUnit test code. Whenever we create any new
project/application, by default the class file [Link] will create automatically
under the package name “[Link]” like as shown below.
MAD Module – II

res (Resources) Folder


It’s an important folder that will contain all non-code resources, such as bitmap images, UI
strings, XML layouts like as shown below.

The res (Resources) will contain a different type of folders that are

Drawable Folder (res/drawable)


It will contain the different types of images as per the requirement of application. It’s a best
practice to add all the images in a drawable folder other than app/launcher icons for the
application development.

Layout Folder (res/layout)


This folder will contain all XML layout files which we used to define the user interface of our
application. Following is the structure of the layout folder in the android application.
MAD Module – II

Mipmap Folder (res/mipmap)


This folder will contain app / launcher icons that are used to show on the home screen. It
will contain different density type of icons such as hdpi, mdpi, xhdpi, xxhdpi, xxxhdpi, to use
different icons based on the size of the device.

Following is the structure of the mipmap folder in the android application.

Values Folder (res/values)


This folder will contain various XML files, such as strings, colors, style definitions and a static
array of strings or integers. Following is the structure of the values folder in android
application.
MAD Module – II

Manifests Folder
This folder will contain a manifest file ([Link]) for our android application.
This manifest file will contain information about our application such as android version,
access permissions, metadata, etc. of our application and its components. The manifest file
will act as an intermediate between android OS and our application.

Following is the structure of the manifests folder in the android application.

Gradle Scripts
In android, Gradle means automated build system and by using this we can define a build
configuration that applies to all modules in our application. In Gradle [Link] (Project),
and [Link] (Module) files are useful to build configurations that apply to all our app
modules or specific to one app module.

Following is the structure of Gradle Scripts in the android application.


MAD Module – II

Following are the important files which we need to implement an app in android studio.

Android Layout File (activity_main.xml)


The UI of our application will be designed in this file and it will
contain Design and Text modes. It will exists in the layouts folder and the structure
of activity_main.xml file in Design mode like as shown below.

We can make required design modifications in activity_main.xml file either


using Design or Text modes. If we switch to Text mode activity_main.xml file will contain a
code like as shown below.

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


<[Link] xmlns:android="[Link]
MAD Module – II

/apk/res/android"
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="[Link]">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</[Link]>

Android Main Activity File ([Link])


The main activity file in the android application is [Link] and it will exist in
the java folder. The [Link] file will contain the java code to handle all the
activities related to our app.

Following is the default code of [Link] file which is generated by our HelloWorld
application.

package [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
}

Android Manifest File ([Link])


Generally, our application will contain multiple activities and we need to define all
those activities in the [Link] file. In our manifest file, we need to mention
the main activity for our app using the MAIN action and LAUNCHER category attributes
in intent filters (<intent-filter>). In case if we didn’t mention MAIN action or LAUNCHER
category for the main activity, our app icon will not appear in the home screen’s list of apps.
MAD Module – II

Following is the default code of [Link] file which is generated by


our HelloWorld application.

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


<manifest xmlns:android="[Link]
package="[Link]" >

<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="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
</application>
</manifest>

These are the main folders and files required to implement an application in android studio.
If you want to see the actual file structure of the project, select Project from
the Project dropdown instead of Android.

Understanding Activities:
An activity is one screen of an app. In that way the activity is very similar to a window in the
Windows operating system.
The most specific block of the user interface is the activity. An Android app contains
activities, meaning one or more screens.

Examples: Login screen, sign up screen, and home screen.

An activity class is per definition a class in Android. Every application which has UI must
inherit it to create a window.

An activity in Android is a specific combination of XML files and JAVA files. It is basically a
container that contains the design as well as coding stuff.

XML files provide the design of the screen and JAVA files deal with all coding stuff like
handles, what is happening, design files, etc. JAVA files and XML files make your activity
complete.

To make an app we need activities that are bound loosely with each other. In the Android
manifest we can organize the activities in parent-child relationships to aid navigation. The
“main activity” is called the first activity.
MAD Module – II

Example: In social media, e-commerce, and other apps, you see the main activity whenever
you open up that app.

Configuring the Manifest

Activities must be declared and their certain attributes must be declared in the manifest so
that we can use the activities in our app. Android manifest is a file that will give you
information about the application.
DECLARE ACTIVITIES
Let’s start by declaring our activity. First, open your manifest file then add an element as a
child of the element.

Example:
<manifest ... >
<application ... >
<activity android:name=".ExampleActivity" />
...
</application ... >
...
</manifest >
seDebugValue(value)

DECLARE INTENT FILTERS


This feature is very powerful. The intent filters tell Android which activities can handle which
actions. If Android is given an intent, it should find out what activities can manage it. This
process is known as intent resolution. Intent filters provide explicit intent and implicit intent.
You can use intent filters by declaring inside the element. This element includes an element
and we can add , optionally. Together these elements will define the type of intent to which
activity will respond.

Example:
<activity android:name=".ExampleActivity"
android:icon="@drawable/app_icon">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
MAD Module – II

LIFECYCLE OF ACTIVITY

An activity goes through a number of states. Activity lifecycle in Android manages the
different states of activity, such as when the activity starts or stops, etc. All of these states
are managed by callback methods.

There are seven callback methods:-

onCreate():- This callback method must be created by you, this is fired when your activity is
created by the system. For example, when you open the app it will call onCreate(), onStart(),
and onResume() methods. These three methods are initiated when you open an app.
MAD Module – II

onStart():- There should always be an onStart() callback after onCreate() finishes. In the
started state users will be able to see the activity but they are not ready for user interaction.
onResume():- In this, activities will be in the foreground and ready for user interaction. You
can understand the use of this callback from this example: “when the user presses the
phone’s answer button it will give onPause() after you end up calling it will again give
onResume()”.
onPause():- This callback occurs when there is a case of another activity starting in front of
the current activity. It is the opposite of onResume(). An example for this callback can be
“when you open the app, that is another app from the notification bar, or open settings
then it will call onPause() and onStop()”.
onStop():- It is the opposite of onStart(). In this case, activity will no longer be visible to the
users.
onRestart():- This occurs when the activity is stopped and before the activity starts again. It
is a less common callback.
onDestroy():- It is opposite of onCreate(). This starts when the system needs to free
memory or when finish() is called. It is used for cleanup which is a very common activity.

[Link] file in android


The [Link] file contains information of your package, including components
of the application such as activities, services, broadcast receivers, content providers etc.

It performs some other tasks also:

 It is responsible to protect the application to access any protected parts by providing the
permissions.
 It also declares the android api that the application is going to use.
 It lists the instrumentation classes. The instrumentation classes provide profiling and other
information. These information are removed just before the application is published etc.

This is the required xml file for all the android application and located inside the root
directory.

A simple [Link] file looks like this:

<manifest xmlns:android="[Link]
package="[Link]"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
MAD Module – II

android:targetSdkVersion="15" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="[Link]" />

<category android:name="[Link]" />


</intent-filter>
</activity>
</application>

</manifest>

Elements of the [Link] file

The elements used in the above xml file are described below.

<manifest>
manifest is the root element of the [Link] file. It has package attribute that
describes the package name of the activity class.

<application>
application is the sub element of the manifest. It includes the namespace declaration. This
element contains several sub elements that declares the application component such as
activity etc.

The commonly used attributes are of this element are icon, label, theme etc.

android:icon represents the icon for all the android application components.

android:label works as the default label for all the application components.

android:theme represents a common theme for all the android activities.

<activity>
activity is the subelement of application and represents an activity that must be defined in
the [Link] file. It has many attributes such as label, name, theme, launchMode
etc.

android:label represents a label i.e. displayed on the screen.

android:name represents a name for the activity class. It is required attribute.


MAD Module – II

<intent-filter>
intent-filter is the sub-element of activity that describes the type of intent to which activity,
service or broadcast receiver can respond to.

<action>
It adds an action for the intent-filter. The intent-filter must have at least one action element.

<category>
It adds a category name to an intent-filter.

Android UI Layouts
introduction to the Layout Editor

The Layout Editor appears when you open an XML layout file.

1. Palette: contains various views and view groups that you can drag into your layout.
2. Component Tree: shows the hierarchy of components in your layout.
3. Toolbar: has buttons that configure your layout appearance in the editor and change
layout attributes.
4. Design editor: lets you edit your layout in Design view, Blueprint view, or both.
5. Attributes: has controls for the selected view's attributes.
MAD Module – II

6. View mode: lets you view your layout in either Code , Split ,
or Design modes. Split mode shows the Code and Design windows at the same
time.
7. Zoom and pan controls: control the preview size and position within the editor.

When you open an XML layout file, the design editor opens by default, as shown in figure 1.
To edit the layout XML in the text editor, click the Code button in the top-right corner of
the window. Note that the Palette, Component Tree, and Attributes panels are not
available while editing your layout in Code view.

Creating the User Interface:


Layouts in Android define the user interface and hold UI controls or widgets that appear on
the screen of an application. Every Android application consists of View and View Group
elements. Since an application contains multiple activities—each representing a separate
screen—every activity has multiple UI components, which are instances of View and View
Group. These components are structured using a hierarchy of View and View Group objects.
View and View Group
A View is defined as an interactive UI 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.

A View Group act as a base class for layouts and layouts parameters that hold other Views
or View Groups and to define the layout properties. They are generally Called layouts.
MAD Module – II

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/JAVA file dynamically

Create a new layout

When adding a new layout for your app, first create a default layout file in your project's
default layout/ directory so that it applies to all device configurations. Once you have a
default layout, you can create layout variations, as described in a section on this page, for
specific device configurations, such as for large screens.

You can create a new layout in one of the following ways:

Use Android Studio's main menu


1. In the Project window, click the module you want to add a layout to.
2. In the main menu, select File > New > XML > Layout XML File.
3. In the dialog that appears, provide the filename, the root layout tag, and the
source set where the layout belongs.
4. Click Finish to create the layout.
Use the Project view
1. Choose the Project view from within the Project window.
2. Right-click the layout directory where you'd like to add the layout.
3. In the context menu that appears, click New > Layout Resource File.
Use the Android view
1. Choose the Android view from within the Project window.
2. Right-click the layout folder.
3. In the context menu that appears, select New > Layout Resource File.
MAD Module – II

Use the Resource Manager


1. In the Resource Manager, select the Layout tab.
2. Click the + button, and then click Layout Resource File.

Layouts in Android UI Design

Layout Managers (or simply layouts) are said to be extensions of the View Group class. They
are used to set the position of child Views within the UI we are building. We can nest the
layouts, and therefore we can create arbitrarily complex UIs using a combination of layouts.
There is a number of layout classes in the Android SDK. They can be used, modified or can
create your own to make the UI for your Views, Fragments and Activities. You can display your
contents effectively by using the right combination of layouts.

Types of Layouts
1. Constraint Layout
Constraint Layout is a flexible layout that allows views to be positioned using
constraints instead of nesting layouts. It helps in reducing the view hierarchy and improves
performance by a lot. It is the most popular and recommended layout for designing complex
interfaces in modern Android applications.

2. Linear Layout
A Linear Layout aligns each of the view in a single direction either a vertical or
a horizontal manner. A layout in vertical manner has a single column of views, whereas in a
layout in horizontal manner, has a single row of views. It supports a weight attribute for each
view that can control the relative size of each view within the available space. However,
excessive nesting of Linear Layouts can lead to performance issues, so it’s best for
straightforward layouts with a few elements.
MAD Module – II

3. Frame Layout
Frame Layout is a simple layout mainly used to hold a single child view, though multiple views
can be stacked on top of each other. It is commonly used for overlays, fragments, and simple
UI components like image views.

4. Relative Layout
Relative layout allows views to be relative to one another or to the parent layout. This makes
positioning flexible as we can position views to the left, right, top, or bottom of other views.
However after Constraint Layout was introduced, the use of Relative Layout has ceased since
Constraint Layout is much better as handling large UIs.
MAD Module – II

5. Table Layout
Table Layout arranges views in a grid-like format using rows and columns, similar to an HTML
table. It is useful for displaying structured data, such as forms or spreadsheets. Each row
consists of multiple Table Row elements, and views within rows can be assigned specific
column spans.

6. Grid Layout
Introduced in Android 4.0 (API level 14), the Grid Layout is an advanced and more flexible
alternative to Table Layout. It divides the screen into a matrix of rows and columns, allowing
precise placement of elements without needing of nested layouts. It is efficient for creating
grid-based UIs like image galleries or dashboards.

7. Coordinator Layout
Coordinator Layout is an advance layout that provides motion and interactive capabilities
between views. It is mostly used for implementing components like the Collapsing Toolbars,
and swipe-to-dismiss behavior. It allows views to work based on user actions, such as
scrolling, swipe gestures and animations.
MAD Module – II

Each of these layouts is designed to scale to suit the screen size of the host device by avoiding
the use of absolute co-ordinates of the positions or predetermined pixel values. This makes
the app suitable for the diverse set of Android devices.

Android - UI Controls
Input controls are the interactive components in your app's user interface. Android provides
a wide variety of controls you can use in your UI, such as buttons, text fields, seek bars,
check box, zoom buttons, toggle buttons, and many more.

UI Elements
A View is an object that draws something on the screen that the user can interact with and
a ViewGroup is an object that holds other View (and ViewGroup) objects in order to define
the layout of the user interface.

You define your layout in an XML file which offers a human-readable structure for the layout,
similar to HTML. For example, a simple vertical layout with a text view and a button looks like
this −

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


<LinearLayout
xmlns:android="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
MAD Module – II

<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button" />
</LinearLayout>

Android UI Controls
There are number of UI controls provided by Android that allow you to build the graphical
user interface for your app.

[Link]. UI Control & Description

TextView
1
This control is used to display text to the user.

EditText
2 EditText is a predefined subclass of TextView that includes rich editing
capabilities.

AutoCompleteTextView
The AutoCompleteTextView is a view that is similar to EditText, except
3
that it shows a list of completion suggestions automatically while the user
is typing.

Button
4 A push-button that can be pressed, or clicked, by the user to perform an
action.

ImageButton
An ImageButton is an AbsoluteLayout which enables you to specify the
5
exact location of its children. This shows a button with an image (instead
of text) that can be pressed or clicked by the user.

CheckBox
An on/off switch that can be toggled by the user. You should use check box
6
when presenting users with a group of selectable options that are not
mutually exclusive.
MAD Module – II

ToggleButton
7
An on/off button with a light indicator.

RadioButton
8
The RadioButton has two states: either checked or unchecked.

RadioGroup
9
A RadioGroup is used to group together one or more RadioButtons.

ProgressBar
10 The ProgressBar view provides visual feedback about some ongoing tasks,
such as when you are performing a task in the background.

Spinner
11
A drop-down list that allows users to select one value from a set.

TimePicker
12 The TimePicker view enables users to select a time of the day, in either 24-
hour mode or AM/PM mode.

DatePicker
13
The DatePicker view enables users to select a date of the day.

Create UI Controls
Input controls are the interactive components in your app's user interface. Android provides
a wide variety of controls you can use in your UI, such as buttons, text fields, seek bars,
check box, zoom buttons, toggle buttons, and many more.

As explained in previous chapter, a view object may have a unique ID assigned to it which
will identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is −

android:id="@+id/text_id"

To create a UI Control/View/Widget you will have to define a view/widget in the layout file
and assign it a unique ID as follows −

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


<LinearLayout
xmlns:android="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView android:id="@+id/text_id"
MAD Module – II

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
</LinearLayout>

Then finally create an instance of the Control object and capture it from the layout, use the
following −

TextView myText = (TextView) findViewById([Link].text_id);


MAD Module – II

Event Handling in Android:

Events are the actions performed by the user in order to interact with the application, for
e.g. pressing a button or touching the screen. The events are managed by the android
framework in the FIFO manner i.e. First In – First Out. Handling such actions or events by
performing the desired task is called Event Handling.

Input event management


 Event Listeners: It is an interface in the View class. It contains a single callback
method. Once the view to which the listener is associated is triggered due to user
interaction, the callback methods are called.
 Event Handlers: It is responsible for dealing with the event that the event listeners
registered for and performing the desired action for that respective event.
 Event Listeners Registration: Event Registration is the process in which an Event
Handler gets associated with an Event Listener so that this handler is called when the
respective Event Listener fires the event.
 Touch Mode: When using an app with physical keys it becomes necessary to give focus
to buttons on which the user wants to perform the action but if the device is touch-
enabled and the user interacts with the interface by touching it, then it is no longer
necessary to highlight items or give focus to particular View. In such cases, the device
enters touch mode and in such scenarios, only those views for which the
isFocusableInTouchMode() is true will be focusable, e.g. plain text widget.

Event Listeners and their respective event handlers


 OnClickListener() – This method is called when the user clicks, touches, or focuses on
any view (widget) like Button, ImageButton, Image, etc. Event handler used for this is
onClick().
 OnLongClickListener() – This method is called when the user presses and holds a
particular widget for one or more seconds. Event handler used for this is
onLongClick().
 OnMenuItemClickListener() – This method is called when the user selects a menu
item. Event handler used for this is onMenuItemClick().
 OnTouch() – This method is called either for a movement gesture on the screen or a
press and release of an on-screen key. Event handler used for this is onTouch().

There are various other event listeners available which can be used for different
requirements and can be found in the official documentation.

Implementing Android Event Handling


Step 1: Open New Project and fill in all the required details.
Step 2: After doing this open your project and we will set the layout and the required Id
of the elements so we can call them easily.
Open the activity_main.xml file. The following code is to be written in this file.

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


MAD Module – II

<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginLeft="100dp"
android:fontFamily="@font/arya_bold"
android:text="DataFlair "
android:textColor="@color/colorPrimaryDark"
android:textSize="50dp" />
<Button
android:id="@+id/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="150dp"
android:layout_marginTop="100dp"
android:fontFamily="@font/arya_bold"
android:text="Click Event" />
<TextView
android:id="@+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#009999"
android:layout_marginLeft="150dp"
android:textSize="20dp"
android:textStyle="bold"
android:layout_marginTop="12dp"/>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:fontFamily="@font/arya_bold"
android:gravity="center"
android:text="See me!"
android:textColor="#009999"
android:textSize="25dp" />
MAD Module – II

</LinearLayout>
Step 3: After writing the code of [Link]. We will now write the code
for main_activity.java as follows:

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import android. [Link];
public class MainActivity extends AppCompatActivity {
Button btn;
TextView tView;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
btn = (Button)findViewById([Link]);
tView = (TextView)findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById([Link]);
[Link]("You've Clicked \n The Event has taken place");
[Link](25);
[Link]([Link]);
[Link]([Link]);
}
});
}
}
Step 4: Now open [Link] in this order – app > src>main>res>values>[Link]

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


<resources>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
</resources>
Step 5: After writing the above codes, we can happily run the application.
After you run the application, the following would be as follows:
MAD Module – II

Now, we will click and see how the onClick() method reacts when we click.

Displaying Messages Through Toast

A Toast is a feedback message. It takes a very little space for displaying while the overall
activity is interactive and visible to the user. It disappears after a few seconds. It
disappears automatically. If the user wants a permanently visible message,
a Notification can be used. Another type of Toast is custom Toast, in which images can be
used instead of a simple message.
MAD Module – II

Example: Toast class provides a simple popup message that is displayed on the current
activity UI screen (e.g. Main Activity).
Constants of Toast class
Constants Description

public static final int LENGTH_LONG displays for a long time

public static final int LENGTH_SHORT displays for a short time


Methods of Toast class

Methods Description

public static Toast makeText(Context context, makes the toast message consist of
CharSequence text, int duration) text and time duration

public void show() displays a toast message

public void setMargin (float horizontalMargin, changes the horizontal and vertical
float verticalMargin) differences

Step-By-Step Implementation

Step 1: Create a New Project in Android Studio

The code for that has been given in both Java and Kotlin Programming Language for
Android.
MAD Module – II

Step 2: Working with the XML Files

Open the “activity_main.xml” file and add a Button to show the Toast message in
a Constraint Layout. Also, Assign an ID to the button component as shown in the image
and the code below. The assigned ID to the button helps to identify and to use files.
android:id="@+id/id_name"
Here the given ID is Button01 This will make the UI of the Application:

Step 3: Working with the MainActivity File


Now, after the UI, this step will create the Backend of the App. For this, Open the
“MainActivity” file and instantiate the component (Button) created in the XML file using
the findViewById() method. This method binds the created object to the UI Components
with the help of the assigned ID.
General Syntax:
ComponentType object = (ComponentType)findViewById([Link]);
MAD Module – II

The syntax for the used component (Click Button):


Button btn = (Button)findViewById([Link].Button01);

Step 4: Operations to Display the Toast Message


Add the listener on the Button and this Button will show a toast message.
[Link](new [Link]() {});
Now, Create a toast message. The [Link]() method is a pre-defined method that
creates a Toast object. Syntax:
public static Toast makeText (Context context, CharSequence text, int duration)

Parameters: This method accepts three parameters:


A. context: A first parameter is a Context object which is obtained by calling
getApplicationContext().
Context context = getApplicationContext();
B. text: The second parameter is your text message to be displayed.
CharSequence text=”Your text message here”
C. duration: The last parameter is the time duration for the message.
int duration=Toast.LENGTH_LONG;
Display the created Toast Message using the show() method of the Toast class.
Syntax:
public void show ()

The code to show the Toast message:


[Link](getApplicationContext(), "This a toast message",
Toast.LENGTH_LONG).show();

Step 5: Now Run the App


Operate it as follows:
 When the app is opened, it displays a “Click” button.
 Click the Click button.
 Then “This a toast message” will be displayed on the screen as a Toast Message.
MAD Module – II

Using the Edit Text Control:


A EditText is an overlay over TextView that configures itself to be editable. It is the predefined
subclass of TextView that includes rich editing capabilities .

EditText Attributes
Following are the important attributes related to EditText control. You can check Android official
documentation for complete list of attributes and related methods which you can use to change
these attributes are run time.

Inherited from [Link] Class −

[Link] Attribute & Description

android:autoText
1 If set, specifies that this TextView has a textual input method and automatically corrects
some common spelling errors.

android:drawableBottom
2
This is the drawable to be drawn below the text.

android:drawableRight
3
This is the drawable to be drawn to the right of the text.

android:editable
4
If set, specifies that this TextView has an input method.

android:text
5
This is the Text to display.
Inherited from [Link] Class −

[Link] Attribute & Description

android:background
1
This is a drawable to use as the background.

android:contentDescription
2
This defines text that briefly describes content of the view.

android:id
3
This supplies an identifier name for this view.

android:onClick
4
This is the name of the method in this View's context to invoke when the view is clicked.

android:visibility
5
This controls the initial visibility of the view.
MAD Module – II

Following is the content of the modified main activity file src/[Link]/[Link].


This file can include each of the fundamental lifecycle methods.

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends Activity {


EditText eText;
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
eText = (EditText) findViewById([Link]);
btn = (Button) findViewById([Link]);
[Link](new OnClickListener() {
public void onClick(View v) {
String str = [Link]().toString();
Toast msg =
[Link](getBaseContext(),str,Toast.LENGTH_LONG);
[Link]();
}
});
}
}

Following will be the content of res/layout/activity_main.xml file –

<RelativeLayout
xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
MAD Module – II

android:layout_alignParentTop="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="18dp"
android:text="@string/example_edittext" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="130dp"
android:text="@string/show_the_text" />
<EditText
android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button"
android:layout_below="@+id/textView1"
android:layout_marginTop="61dp"
android:ems="10"
android:text="@string/enter_text" android:inputType="text"
/>
</RelativeLayout>
Following will be the content of res/values/[Link] to define these new constants –

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


<resources>
<string name="app_name">demo</string>
<string name="example_edittext">Example showing
EditText</string>
<string name="show_the_text">Show the Text</string>
<string name="enter_text">text changes</string>
</resources>
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 −
MAD Module – II

Choosing Options with Checkbox

In android, CheckBox is a two-states button that can be either checked (ON) or unchecked
(OFF) and it will allow users to toggle between the two states (ON / OFF) based on the
requirements.

Generally, we can use multiple CheckBox controls in android application to allow users to
select one or more options from the set of values.

Following is the pictorial representation of using CheckBox control in android applications.

By default, the android CheckBox will be in the OFF (Unchecked) state. We can change the
default state of CheckBox by using android:checked attribute.

In case, if we want to change the state of CheckBox to ON (Checked), then we need to


set android:checked = “true” in our XML layout file.

In android, we can create CheckBox control in two ways either in the XML layout file or
create it in the Activity file programmatically.

Android CheckBox Control Attributes


The following are some of the commonly used attributes related to CheckBox control in android
applications.

Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of checkbox

android:gravity It is used to specify how to align the text like left, right, center, top, etc.

android:text It is used to set the text for a checkbox.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.


MAD Module – II

Attribute Description

android:background It is used to set the background color for checkbox control.

android:padding It is used to set the padding from left, right, top and bottom.

android:onClick It’s the name of the method to invoke when the checkbox clicked.

android:visibility It is used to control the visibility of control.

Android CheckBox Control Example


Following is the example of defining multiple CheckBox controls and one Button control
in LinearLayout to get the selected values of CheckBox controls when we click on Button in
the android application.

Create a new android application using android studio and give names as CheckBoxExample.
In case if you are not aware of creating an app in android studio check this article Android
Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown
below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="@+id/chkJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:text="Java"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Python"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
MAD Module – II

android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Android"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkAngular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="AngularJS"
android:onClick="onCheckboxClicked"/>
<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Get Details" />
</LinearLayout>
If you observe above code we created a multiple CheckBox controls and one Button control
in XML Layout file.

Once we are done with the creation of layout with required controls, we need to load the
XML layout resource from our activity onCreate() callback method, for that open
main activity file [Link] from \java\[Link] path and
write the code like as shown below.

[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {


CheckBox android, java, angular, python;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
android = (CheckBox)findViewById([Link]);
angular = (CheckBox)findViewById([Link]);
java = (CheckBox)findViewById([Link]);
python = (CheckBox)findViewById([Link]);
Button btn = (Button)findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
MAD Module – II

String result = "Selected Courses";


if([Link]()){
result += "\nAndroid";
}
if([Link]()){
result += "\nAngularJS";
}
if([Link]()){
result += "\nJava";
}
if([Link]()){
result += "\nPython";
}
[Link](getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
});
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
String str="";
// Check which checkbox was clicked
switch([Link]()) {
case [Link]:
str = checked?"Android Selected":"Android Deselected";
break;
case [Link]:
str = checked?"AngularJS Selected":"AngularJS Deselected";
break;
case [Link]:
str = checked?"Java Selected":"Java Deselected";
break;
case [Link]:
str = checked?"Python Selected":"Python Deselected";
break;
}
[Link](getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
}
If you observe above code we are calling our layout using setContentView method in the
form of [Link].layout_file_name in our activity file. Here our xml file name
is activity_main.xml so we used file name activity_main and we are getting the status
of CheckBox controls when they Select / Deselect and getting the selected CheckBox control
values on Button click.

Generally, during the launch of our activity, onCreate() callback method will be called by
android framework to get the required layout for an activity.

Output of Android CheckBox Example


When we execute the above example using the android virtual device (AVD) we will get a
result like as shown below.
MAD Module – II

If you observe above result, we are able to get the status


of checkboxes while selecting / deselecting and getting all the selected CheckBox values
on button click.

This is how we can use CheckBox control in android applications to allow users to select one
or more options based on our requirements.

Choosing Mutually Exclusive Items Using Radio Buttons.

Android radio button is a widget that can have more than one option to choose from. The
user can choose only one option at a time. Each option here refers to a radio button and all
the options for the topic are together referred to as Radio Group. Hence, Radio Buttons are
used inside a RadioGroup.
For Example:
MAD Module – II

Example Of RadioButton And RadioGroup in Android Studio:


Example of Radiobutton in Android where we display five radio buttons with background and
other attributes. The radio buttons are used to select your favorite WWE superstar with one
“submit” button. Below is the final output, download code and step by step explanation of
tutorial:
Step 1: Create a new project and name it RadioButtonExample
Select File -> New -> New Project and Fill the forms and click “Finish” button.
Step 2: Open res -> layout -> activity_main.xml (or) [Link] and add following code:
In this step we open an xml file and add the code for displaying 5 RadioButton and one normal
button.

<LinearLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#e0e0e0"
android:orientation="vertical">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select your favourite wwe SuperStar :: "
android:textColor="#000"
android:textSize="20sp"
android:textStyle="bold" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/johnCena"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:checked="true"
android:text="@string/johnCena"
android:textColor="#154"
android:textSize="20sp"
android:textStyle="bold" />
<RadioButton
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:checked="false"
MAD Module – II

android:text="@string/randyOrton"
android:textColor="#154"
android:textSize="20sp"
android:textStyle="bold" />
<RadioButton
android:id="@+id/romanReigns"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:checked="false"
android:text="@string/romanReigns"
android:textColor="#154"
android:textSize="20sp"
android:textStyle="bold" />
<RadioButton
android:id="@+id/goldBerg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:checked="false"
android:text="@string/goldBerg"
android:textColor="#154"
android:textSize="20sp"
android:textStyle="bold" />
<RadioButton
android:id="@+id/sheamus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:checked="false"
android:text="@string/sheamus"
android:textColor="#154"
android:textSize="20sp"
android:textStyle="bold" />

</RadioGroup>
<Button
android:id="@+id/submitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#0f0"
android:padding="10dp"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>

Step 3: Open src -> package -> [Link]


In this step we open MainActivity and add the code to initiate the RadioButton and normal
button. We also perform click event on button and display the selected superstar’s name by
using a Toast.

package [Link];
MAD Module – II

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

RadioButton johnCena, randyOrton, goldBerg, romanReigns, sheamus;


String selectedSuperStar;
Button submit;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
johnCena = (RadioButton) findViewById([Link]);
randyOrton = (RadioButton) findViewById([Link]);
goldBerg = (RadioButton) findViewById([Link]);
romanReigns = (RadioButton) findViewById([Link]);
sheamus = (RadioButton) findViewById([Link]);
submit = (Button) findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
if ([Link]()) {
selectedSuperStar = [Link]().toString();
} else if ([Link]()) {
selectedSuperStar = [Link]().toString();
} else if ([Link]()) {
selectedSuperStar = [Link]().toString();
} else if ([Link]()) {
selectedSuperStar = [Link]().toString();
} else if ([Link]()) {
selectedSuperStar = [Link]().toString();
}
[Link](getApplicationContext(), selectedSuperStar, Toast.L
ENGTH_LONG).show(); // print the value of selected super star
}
});
}
}

Step 4: Open res -> values -> [Link]


In this step we open String file which is used to store string data of the app.

<resources>
<string name="app_name">RadioButtonExample</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="randyOrton">Randy Orton</string>
<string name="johnCena">John Cena</string>
<string name="romanReigns">Roman Reigns</string>
<string name="goldBerg">Gold Berg</string>
<string name="sheamus">Sheamus</string>
</resources>
MAD Module – II

Run The App:


Now run the App in Emulator and you will see 5 RadioButton in RadioGroup listing WWE
superstar name. Now choose your favorite one and click on Submit Button. The name will be
displayed on Screen.

You might also like