0% found this document useful (0 votes)
14 views48 pages

Unit 3

This document provides an overview of user interface design for Android applications, detailing UI components, layout managers, and the use of XML for defining layouts. It covers the creation of menus, notifications, styles, themes, and animations, emphasizing best practices for developing a visually appealing and functional user interface. Additionally, it explains the role of adapters in connecting data to views and the importance of managing media files within the application.
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)
14 views48 pages

Unit 3

This document provides an overview of user interface design for Android applications, detailing UI components, layout managers, and the use of XML for defining layouts. It covers the creation of menus, notifications, styles, themes, and animations, emphasizing best practices for developing a visually appealing and functional user interface. Additionally, it explains the role of adapters in connecting data to views and the importance of managing media files within the application.
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
You are on page 1/ 48

3.

1 User Interface Design

This chapter will examine the various UI components of the Android screen. This chapter
also covers UI design best practises and describes how to develop a UI.

UI screen elements
A typical user interface of an android application consists of action bar and the application
content area.

These components have also been shown in the image below

Fig1 Android UI Progress screen

Understanding Screen Components

The activity is the fundamental Android application component. An xml file defines a user
interface. During compilation, each XML element is translated into a corresponding Android
GUI class with attributes represented by methods.

View and ViewGroups

Views constitute the activity. A view is nothing more than an on-screen widget. It might be a
button, etc. Multiple views can be aggregated into a single GroupView. ViewGroup example
includes layouts.
3.2 Android Layout Managers

A View object, which is formed from the View class and fills a rectangular area on the screen
and is responsible for rendering and event processing, is the fundamental component of the
user interface. View is the foundation class for widgets, which are used to generate interactive
user interface elements such as buttons, text fields, and so on.

The ViewGroup is a subclass of View that offers an unseen container for holding and defining
the layout properties of other Views or ViewGroups.At the third level, we have various layouts
that are subclasses of the ViewGroup class, and a typical layout defines the visual structure of
an Android user interface. Layouts can be created at runtime using View/ViewGroup objects,
or they can be declared using the main layout.xml file located in the res/layout folder of your
project.

Fig2 Layout Params

This lesson focuses on designing your GUI using XML file-defined layouts. A layout may
include widgets like as buttons, labels, and textboxes, among others. The following is a simple
illustration of an XML file with LinearLayout.
Once your layout has been built, you may load the layout resource in your Activity.onCreate()
callback function, as seen below.

Android Layout Types


There are number of Layouts provided by Android which you will use in almost all the
Android applications to provide different view, look and feel.
Layout Attributes

Each layout has a collection of attributes that define its visual qualities. There are only a few
attributes that are shared by all layouts, while others are unique to each style. The following
attributes are shared and will be applied to all layouts.
Here, width and height are the layout/view dimensions that can be set in dp (Density-
independent Pixels), sp (Scale-independent Pixels), pt (Points which is 1/72 of an inch), px
(Pixels), mm (Millimeters), and lastly in pixels (inches).
• android:layout_width=wrap_content tells your view to size itself to the dimensions
required by its content.

• android:layout_width=fill_parent tells your view to become as big as its parent


view.

View Identification

A view object may be assigned a unique ID that uniquely identifies the view within the tree.
This is the syntax for an ID within an XML tag

android:id="@+id/my button"

Following is a basic explanation of the @ and + symbols


The at-symbol (@) at the start of the ID string instructs the XML parser to parse and extend
the remainder of the ID string and identify it as an ID resource.

This is a new resource name that must be generated and added to our resources, as indicated
by the plus sign (+). To construct a view object instance and capture it from the layout, use the
code below:

ButtonmyButton=(Button)findViewById(R.id.my button);

3.3 Adapters

An Adapter object functions as a bridge between an AdapterView and the view's underlying
data. The Adapter allows access to the data objects. The Adapter is also accountable for
creating a View for each data set item.
3.4 Menu
Options Menu
An Adapter object functions as a bridge between an AdapterView and the view's underlying
data. The Adapter allows access to the data objects. The Adapter is also accountable for
creating a View for each data set item.

Using the menu layout from above, we get the following options menu:

Fig3. Option Menu


As discussed, let’s go over the values that can be given for the showAsAction attribute.
• collapseActionView - if this item has an action view associated with it, it will become
collapsible(from API 14 and above)
If we go ahead and change the last item in our menu to showAsAction=”never”, we get the
following

Fig4. Change in Menu


The third menu item moved to the overflow menu
Contextual Menu
This menu appears when a user performs a long click on one of your UI elements. The options
found in this menu affect what UI element the user made the click on. It is common to use this
type of menu in list or grid views, where the user’s interaction with each item can lead to a
specific action.Imagine a scenario where you have an application with an image, and you want
to present to the user several choices when they click on the image.A context menu can appear
in two ways.
1. A floating menu
2. An action bar at the top of your application
We will only demonstrate how to use the first option, but you can read more about the second
option here, using the following XML.
The code needed to enable context menu for our main activity’s layout, We will get the
following window.

Fig5. Context Menu


When performing a long click on the text, the context menu appears
Popup Menu
A popup menu is a sort of menu that features a vertical list of items. This list is associated with
the view selected by the user to open this menu. It is essential to remember, while selecting a
popup menu, that you do not want the user's selection to influence the previously-selected
content.We will utilize the same menu XML structure as previously, but we must add the
following code to our activity.
When a click occurs, the showPopupMenu method must be invoked.We will obtain the same
outcome as in the previous image, but without requiring the user to do a long click.

Icons In Popup Menus

Now I understand why you are likely here: you want to know how to add icons to menus.While
I will demonstrate how to accomplish this, it is important to note that this feature is not enabled
for popup menus and may result in unexpected behaviour. You can accomplish this by
activating the setForceShowIcon flag using reflection.

The showPopupMenu method should be called when a click happens.We will get the same
result as the previous screenshot, but without the need for the user to perform a long click.
Fig6. Icons in popup menu

3.5 Notifications

When you instruct the system to send a notification, it initially appears in the notification area
as an icon.To view the notification's details, the user opens the notification drawer. Both the
notification area and the notification drawer are user-accessible system-controlled locations. A
notification is a message that your programme can display to the user outside of the standard
user interface.

Fig7. Notifications in the notification area.


The Android Toast class provides a convenient method for displaying notifications to users;
however, these alerts are not persistent, meaning they expire after a few seconds.

Create and Send Notifications

You may easily generate a notice. Follow the steps below to create a notification in your
application:

Step 1: Create the Notification Builder

Create a notification builder using NotificationCompat.Builder.build as the initial step (). You
will utilise Notification Builder to configure Notification attributes such as its tiny and large
icons, title, and priority, among others.
Step 2: Setting Notification Properties

Once you have a Builder object, you can set its Notification properties according to your needs
by utilising the Builder object. However, this must be set to at least following.

• A small icon, set by setSmallIcon()

• A title, set by setContentTitle()

• Detail text, set by setContentText()

You can configure numerous optional attributes for your notification. To learn more about
them, consult the NotificationCompat.Builder documentation.

Step 3: Attach Actions

This is a needed component if you wish to attach an action to the notice. An action enables
users to navigate directly from the notification to an Activity within your application, where
they can view one or more events or perform additional tasks.

The action is specified by a PendingIntent that contains an Intent that launches an Activity in
your application. To correlate a PendingIntent with a gesture, invoke the corresponding
NotificationCompat.Builder function. For instance, if you want Activity to begin when the user
clicks the notice text in the notification drawer, you add the PendingIntent by calling
setContentIntent ().

A PendingIntent object enables you to conduct an action on behalf of your application, often
at a later time, regardless of whether your application is running or not.We utilise a stack
builder object that has a synthetic back stack for the started Activity. This ensures that
navigating backward from the Activity leads to the Home screen when the programme is
closed.
.

Step 4: Issue the notification

Finally, you deliver your notification by passing the Notification object to the system via the
NotificationManager.notify() method. Before notifying the builder object, you must ensure that
its build() method has been called. This function combines all previously set settings and
returns a new Notification object.

The NotificationCompat.Builder Class


The NotificationCompat.Builder class simplifies the management of all flags and facilitates the
construction of standard notification layouts. The following are some of the most important
and commonly used NotificationCompat.Builder methods.

Creating a Notification
In a NotificationCompat.Builder object, you provide the UI details and actions for a
notification.To create the actual notification,you must call NotificationCompat.Builder.build(
), which returns a Notificationobject containing your specifications. Calling
NotificationManager.notify passes the Notification object to the system in order to send the
notification ().

Required notification contents

A Notification object must contain the following:


• A small icon, set by setSmallIcon()

• A title, set by setContentTitle()

• Detail text, set by setContentText()

All additional options and contents of notifications are optional. To learn more about them,
consult the NotificationCompat.Builder documentation.

Notification actions

Although actions are optional, you must include at least one in your notification. An
action enables users to navigate directly from the notification to an Activity within your
application, where they can view one or more events or perform additional tasks.

Multiple actions may be provided by a notification. Always define the action that is
triggered when the user taps the notification; typically, this action opens an Activity within
your application. As of Android 4.1, you can also add buttons to notifications that do extra
actions, such as snoozing an alarm or reacting instantly to a text message. If you employ
additional action buttons, you must also make their functionality available in an Activity within
your app; for more information, see the section Handling compatibility.

The action itself is defined within a Notification by a PendingIntent holding an Intent


that launches an Activity in your application. To correlate thePendingIntent with a gesture,
invoke the corresponding NotificationCompat.Builder function. For instance, if you want
Activity to begin when the user clicks the notice text in the notification drawer, you add the
PendingIntent by calling setContentIntent ().

The most typical action scenario occurs when the user clicks a notification to initiate an
Activity. Additionally, you can initiate an Activity when the user dismisses a notification. After
Android 4.1, you can launch an Activity from an action button. To learn more, consult
theNotificationCompat.Builder documentation.

3.6 Styles and Themes


A style resource specifies the look and feel of a user interface. A style can be applied to a single
View (from within a layout file) or to an Activity or application as a whole (from within the
manifest file).
Defining Styles
A style is defined in a distinct XML resource than the XML that provides the layout. This XML
file exists in the res/values/ directory of your project and will have the required resources> root
node for the style file. The name of the XML file is arbitrary, but the.xml extension is required.

You can declare many styles in a single file using the style> tag, but each style must have a
distinct name. As demonstrated here, Android style characteristics are set using the <item> tag.

Depending on the style attribute, the value of item> can be a keyword string, a hex colour, a
reference to another resource type, or another value.

Using Styles
Once your style has been defined, you can utilise it in your XML Layout file by using the style
attribute.
3.6.1 Android Themes
Hope you grasped the concept of Style; let's now attempt to comprehend what a Theme is. A
theme is simply an Android style that is applied to a complete Activity or application, as
opposed to a single View.Therefore, when a style is applied as a theme, each View within an
Activity or application will apply each style property that it supports. For instance, you can
apply the sameCustomFontStyle style as a theme to an Activity, and all text within that Activity
will subsequently use a green monospace font.
To set a theme for all activities in your application, enter theAndroidManifest.xml file and add
the android:theme attribute with the style name to the application> tag. For instance

3.7 Drawing and Working with Animation

Animation is the process of giving any view, picture, or text a motion effect. With the aid of
animation, you can add motion to a certain view or alter its shape. In Android, animation is
typically utilised to create a visually rich user interface. There are essentially three sorts of
animations.

1. Property Animation

Property Animation is one of the robust frameworks that enables the animation of virtually
everything. This is one of the powerful and versatile animations that Android 3.0 introduces.
Other than views, property animation may be used to apply any animation to CheckBox,
RadioButton, and widget elements.

Fig8. Property Animation


2. View Animation

View Animation can be used to add animation to a specific view in order to accomplish
tweened animation. Tweened animation computes animation data including size, rotation, start
point, and end point. This animation is slower and less versatile than others. If we wish to
expand a certain layout in that location, we can utilise View Animation as an
example.Expandable RecyclerView provides a demonstration of View Animation.

Fig9. View Animation


3. Drawable Animation

Drawable Animation is used when animating one image on top of another. The easiest way to
comprehend how to animate drawable is to sequentially load a series of drawables to create an
animation. A simple example of drawable animation may be observed in the splash screen and
logo animation of numerous mobile applications.

Fig10. Drawable Animation

Important Methods of Animation

Example

Now we shall examine the Simple Example for ImageView animations.Note that we will
implement this project using the Java programming language.

Step 1: Create a New Project


Refer to How to Create/Start a New Project in Android Studio to create a new project in
Android Studio. Note that Java should be selected as the programming language.

.Step 2: Working with the strings.xml file


The Strings.xml file may be accessed via app > res > values > strings.xml. This is a fragment
of the strings.xml file.
Step 3: Add the Google repository to the build.gradle file of the application project if it is not
there by default.

Include all Jetpack components from the Google Maven repository into the build.gradle file.

Step 4: Working with the activity_main.xml file


Create ImageView and buttons that will add animation to the view in activity main.xml. Go to
app > resources > layout > activity main.xml. Below is the activity main.xml file's source code.
Step 5: Create 6 different types of animation for ImageView

In order to create new animations, we must build a new directory to store all animations.
Navigate to the application > resources > right-click on resources > new > directory > name
the directory "anim." In this directory, our animations will be created. To create a new anim,
right-click the anim directory and select Animation Resource File. Then, give the file a name.
Below is the code for six distinct animations.
1) Blink Animation

2) Fade Animation
XML

3) Move Animation
4) Rotate Animation

5) Slide Animation

6) Zoom Animation
Step 6: Working with the MainActivity.java file

The ImageView can be animated by clicking a certain Button. Navigate to app > java > the
name of your app's package > MainActivity.java.
}
Note: Drawables and strings can be found in the drawable folder and strings.xml file.
Drawables can be found from the app > res > drawable.
Output:

Video Player

Fig11. Video player contains Animation


3.8Android.media

Provides classes and annotations for managing different audio and video media interfaces.
Media files can be played and, in some situations, recorded using the Media APIs. Play MP3s
or other music files, ringtones, gaming sound effects, or DTMF tones, for example. Audio and
video are also included in this (e.g., play a video streamed over the web or from local storage).
Other specialised classes in the package enable users to manage audio routing (to the device
or a headphone), regulate ringtones and phone vibrations, and recognise faces in Bitmaps
(AudioManager).

3.8.1 Android Audio

Through Android's built-in microphone, you may record and store or playback audio on your
phone. There are other ways to accomplish this, but the MediaRecorder class is the most
prevalent.Android provides MediaRecorder class to record audio or video. To utilise the
MediaRecorder class, you must first create an instance of the class. The syntax is shown below.

Set the source, output, and encoding formats as well as the output file. Their syntax is provided
in the next section.

After defining the audio source, format, and output file, the two fundamental methods prepare
and start can be called to begin recording audio.

In addition to these methods, the MediaRecorder class includes other methods that provide
greater control over audio and video recording.
Android Media Player Example

Android's MediaPlayer class enables the playback and control of audio files.Here, we will
examine a straightforward example of playing an audio file. On the following page, we will
see an example of audio playback control, including start, stop, pause, etc.

The android.media.MediaPlayer class is used to control the audio or video files.

There are numerous MediaPlayer class methods. Among them are the following
Activity class

Let's write the code for the audio file's playback. Here, we will play the maine.mp3 file located
in the sdcard/Music folder..
Android MediaPlayer Controlling audio example
Let's examine an example of how to start, stop, and pause audio playback.

activity_main.xml

Drag three buttons from the palette to play, pause, and stop audio. Now the xml file will seem
as follows
Activity class
Let's write the code for the audio player's start, pause, and stop functions.

.
Output:

Fig12. Audio player

3.8.2 Media Recording in Android

It is Used to record audio and video. The recording control is based on a simple state machine
as shown below.

Fig13. Media Recorder State Diagram


3.9 Sensors

The majority of Android-powered smartphones come with in-built sensors that track motion,
orientation, and different environmental factors. These sensors are helpful if you wish to track
three-dimensional device movement or location or track changes in the environment close to
a device because they can deliver raw data with great precision and accuracy. For instance, a
game may monitor gravity sensor readings from a device to deduce complicated user gestures
and actions like tilt, shake, rotation, or swing. Similar to how a weather application might
compute and provide the dewpoint using a device's temperature and humidity sensors, a travel
application might compute and report a compass bearing using a device's geomagnetic field
sensor and accelerometer.The Android platform supports three broad categories of sensors:

1. Motion Sensors
2. Position Sensors
3. Environment Sensors
Motion sensors
These sensors track forces along three axes, including rotational forces and acceleration forces.
Gyroscopes, accelerometers, gravity sensors, and rotating vector sensors fall under this group.
Position sensors

These sensors gauge a device's precise location. Magnetometers and orientation sensors fall
under this category.

Environmental sensors
These sensors collect data on a range of environmental factors, including humidity, lighting,
and the temperature and pressure of the surrounding air. Barometers, photometers, and
thermometers all fall under this category.
Using the Android sensor framework, you may access any sensors that are installed on the
device and obtain their raw data. You can complete a wide range of sensor-related tasks with
the aid of the sensor framework's classes and interfaces. For instance, you could utilise the
sensor framework to carry out the following tasks.

• Discover the sensors a device has available.. Ascertain the specifications of each sensor,
including the manufacturer, resolution, power needs, and maximum range.
• Gather raw sensor data and establish the minimal pace of sensor data gathering..

• Register and deregister sensor event listeners that keep track of changes in the sensors..

3.9.1 Location Based Services


Using the Android Location Manager

Working with the java file

Implement a LocationListener and make a global object for the LocationManager and
implement all the unimplemented methods.

Snippet2:

We must call the requestLocationUpdates function to obtain the user's current location when it
is updated.

Snippet3:

The parameters of this function are as follows:

To print the current location if it was changed


In the onLocationChanged method, the location will be displayed via a toast. We will use the

getLatitude() and getLongitude() functions of a location type variable to obtain the current

position.

Use the below code to print the location.

Snippet4:

However, what if the GPS is disabled?


This event can be handled via the onProviderDisabled function. If the GPS is disabled, our
application must be redirected to the device's Location settings.
We will accomplish this using the code below.
.Snippet5:

Listing 1: The complete code for Android’s MainActivity file :


How do I use an emulator to test the GPS Location management application?

Select Window > Open viewpoint > DDMS

Select the emulator on which you wish to work.

Select the tab for Emulator Control.

Transfer the location specified in the Location Control section.

How do I check the GPS Location manager application in an emulator?


1. Go to Window > Open perspective > DDMS
2. Choose the emulator you want to work on.
3. Go to the Emulator Control tab.
4. Pass the location from the Location Control section.

Google Maps in Android


Android permits the incorporation of Google Maps into our application. You can display any
location on the map, as well as different routes, etc. You can also modify the map according to
your preferences.

Google Map - Layout file


Now you have to add the map fragment into xml layout file. Its syntax is given below −

In addition to adding the Google Map API key to the AndroidManifest.XML file, you must also
add other permissions. The syntax is shown below.

Customizing Google Map


You can easily customize google map from its default view , and change it according to your
demand.

Adding Marker

You can place a maker with some text over it displaying your location on the map. It can be
done by via addMarker() method. Its syntax is given below −

Channing Map Type


You can also modify the MAP's kind. There are four distinct sorts of maps, and each provides
a unique perspective. These are Normal, Hybrid, Satellite, and terrain types. You may utilise
them as indicated below:

Enable/Disable zoom
You can also enable or disable the zoom gestures in the map by calling
the setZoomControlsEnabled(boolean) method. Its syntax is given below.

Apart from these customization, there are other methods available in the GoogleMapclass ,
that helps you more customize the map. They are listed below:

S.No Method & Description

1 addCircle(CircleOptions options)
This method add a circle to the map

addPolygon(PolygonOptions options)
2
This method add a polygon to the map

addTileOverlay(TileOverlayOptions options)
3
This method add tile overlay to the map

animateCamera(CameraUpdate update)
4
This method Moves the map according to the update with an animation

clear()
5
This method removes everything from the map.

getMyLocation()
6
This method returns the currently displayed user location.

moveCamera(CameraUpdate update)
7 This method repositions the camera according to the instructions defined in the
update

setTrafficEnabled(boolean enabled)
8
This method Toggles the traffic layer on or off.

snapshot(GoogleMap.SnapshotReadyCallback callback)
9
This method Takes a snapshot of the map

stopAnimation()
10
This method stops the camera animation if there is one in progress

Example

Here is an example demonstrating the use of GoogleMap class. It creates a basic Mobile
application that allows you to navigate through the map.

To experiment with this example , you can run this on an actual device or in an emulator.

Create a project with google maps activity as shown below −


It will open the following screen and copy the console url for API Key as shown below:

Copy this and paste it to your browser. It will give the following screen:

Click on continue and click on Create API Key then it will show the following screen
Here is the content of activity_main.xml.

In the below code we have given sample latitude and longitude details:
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.

The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key
that is used to sign the APK for publishing.
You can define the keys for the debug and
release targets in src/debug/ and src/release/.

Output should be like this

You might also like