Unit 3
Unit 3
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.
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.
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.
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.
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.
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"
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:
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.
You may easily generate a notice. Follow the steps below to create a notification in your
application:
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.
You can configure numerous optional attributes for your notification. To learn more about
them, consult the NotificationCompat.Builder documentation.
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.
.
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.
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 ().
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 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.
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
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.
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.
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.
Example
Now we shall examine the Simple Example for ImageView animations.Note that we will
implement this project using the Java programming language.
Include all Jetpack components from the Google Maven repository into the build.gradle file.
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
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).
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.
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:
It is Used to record audio and video. The recording control is based on a simple state machine
as shown below.
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..
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:
getLatitude() and getLongitude() functions of a location type variable to obtain the current
position.
Snippet4:
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.
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 −
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:
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.
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/.