0% found this document useful (0 votes)
23 views29 pages

ch3 Mad

This document outlines the fundamentals of UI components and layouts in Android development, emphasizing the importance of user interface design and the structure of Android applications. It details the directory structure of an Android project, including the roles of the manifests, java, and res folders, as well as the various UI components and layouts available. Additionally, it covers the process of creating a new project in Android Studio and the basic building blocks of Android UI, such as Views and ViewGroups.

Uploaded by

khn.salman901
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)
23 views29 pages

ch3 Mad

This document outlines the fundamentals of UI components and layouts in Android development, emphasizing the importance of user interface design and the structure of Android applications. It details the directory structure of an Android project, including the roles of the manifests, java, and res folders, as well as the various UI components and layouts available. Additionally, it covers the process of creating a new project in Android Studio and the basic building blocks of Android UI, such as Views and ViewGroups.

Uploaded by

khn.salman901
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/ 29

3…

UI Components
and Layouts
Chapter Outcomes...
▣ Explain with relevant analogy the given directory structure.
▣ Describe the steps to use the given Android rich UI component.
▣ Describe the steps to use the given type of Layout.
▣ Develop the given basic Android application.

Learning Objectives…
▣ To learn Control Flow and Directory Structure in Android
▣ To study Components of a Android Screen
▣ To understand Fundamental UI Design
▣ To learn various Layouts in Android (Linear, Absolute, Frame, Table, Relative etc.)

3.0 INTRODUCTION
• Designing an user interface, or UI, will be one of your most important tasks during Android
development. Android app's User Interface (UI) is everything that the user can see and interact with.
Android provides a variety of pre-built UI components such as structured layout objects and UI
controls that allows building the Graphical User Interface (GUI) for the app. Android also provides
other UI modules for special interfaces such as dialogs, notifications, and menus.
• Understanding layouts is important for good Android application design. A layout defines the
structure for a user interface in your app, such as in an activity. All elements in the layout are built
using a hierarchy of View and ViewGroup objects.
• A View is considered as a basic building block for a Android User Interface (UI) A View usually draws
something the user can see and interact with. Whereas a ViewGroup is an invisible container that
defines the layout structure for View and other ViewGroup objects.
• The View objects are usually called "widgets" and can be one of many subclasses, such
as Button or TextView. The ViewGroup objects are usually called "layouts" can be one of many types
that provide a different layout structure, such as LinearLayout.
• Input controls are the interactive components in your app's user interface. Android provides a wide
variety of controls we can use in our UI, such as buttons, text fields, seek bars, check box, zoom
buttons, toggle buttons, and many more.
• The Android directory is the place to put all our files, in whatever folder hierarchy we want.
3.1 CONTROL FLOW
• The control flow of an Android application is given in following steps:

[3.1]
Mobile Application Development 3.2 UI Components and Layouts

Step 1: Click on Android Studio icon

Fig. 3.1

Step 2: Select File → New → New Project

Fig. 3.2

Step 3: Give the Project Name and click ‘Next’


Mobile Application Development 3.3 UI Components and Layouts

Fig. 3.3

Step 4: Select your SDK to and click next Target Android Devices

Fig. 3.4

Step 5: To add the project on mobile select the proper activity here we select the empty activity and
click Next
Mobile Application Development 3.4 UI Components and Layouts

Fig. 3.5

Step 6: Give the activity name and click finish.

Fig. 3.6

Android Studio Screen/Window Elements (Components):


• Fig. 3.7 shows Android Studio is an Integrated Development Environment (IDE).

Fig. 3.7

• For understanding the different components of just split the Android Window into parts and give
some numbering (See Fig. 3.7).
1. Menu Bar: Menu Bar contains the drop-down menus to perform different functions.
2. Toolbar: Toolbar contains graphical view of some commonly usable buttons.
3. Navigation Bar: Navigation Bar shows the selected file hierarchy which helps developer to
directly navigate to the parent directories of the file or switch between different files.
Mobile Application Development 3.5 UI Components and Layouts

4. Tool Buttons Bar: Tools Buttons bar allows to switch between different tools in different
windows (Project Tool, Preview, Console Windows).
5. Project Tool Window: There three project tool windows in the interface which allows developer
to use in different ways. Project Tool Window in the left side allows developer to navigate
through all the tools provided in the left side Tool Buttons such as Project hierarchy view,
Favourites, Structure view etc.. Right side Project Tool Window allows to navigate between the
right Tool Buttons like Application Interface Preview on different devices, Gradle functions etc..
Bottom Project Tool Window allows to navigate between the bottom Tool Buttons like Terminal,
Run, Android etc.
6. Editor Window: Editor window open the selected file to allows developer to edit them as per the
requirements.
7. Status Bar: The status bar displays informational messages about the project and the activities
of Android Studio. It also contain a button in the far left corner which lists all the tools menu
button. Hovering over items or button in the status bar will provide a description of that field.
3.2 DIRECTORY STRUCTURE
• The Project tool window has several views, including the Android view, the Project view, and
the Packages view. Each view shows the same stuff, but each view organizes this stuff a bit
differently.
• The button just at above the left pane (shown by the arrow) (See Fig. 3.8) is used to open the selection
box for choosing the preferred method of viewing the file hierarchy.

Fig. 3.8 Fig. 3.9

• Android and Project are the most useful views, though the Android view may hide certain folders
from we. By default, Android Studio will set the view to Android. The Project tool window provides a
simple tree interface with files and nested folders that we can toggle.
• When we create an application in Android Studio, we find that the project is divided into an App
folder and Gradle scripts.
Mobile Application Development 3.6 UI Components and Layouts

Fig. 3.10

• The App folder contains three subfolders (manifests, java and res) that make up our application.
They are divided so that it should be fairly easy to determine which resources go in which folder.
• If we expand all of the folders in the project explorer we will see a vast array of files and folders. Most
of them are managed by Android Studio. We will focus on the key folders and file types that we will
be using as Android developers.

Fig. 3.11
Mobile Application Development 3.7 UI Components and Layouts

1. Manifests Folder
• This is where we would put our manifest files. Most Android apps have single manifest file. But an
app may have several manifest files due to application versioning, or for supporting specific
hardware.
• A AndroidManifest.xml file is generated inside manifest folder by Android Studio when we create a
project. This file contains the configuration parameters of the project such as permissions, services
and additional libraries.
• A manifest file also provides information to the OS and Google Play store about your app.
2. Java Folder:
• Let us take a look at what is in the java folder. This is the folder in our project where we will be
storing all of the source code files written in Java programming language.
• A MainActivity.java is automatically created in this folder by Android Studio. All of your classes will
be available here, and Android Studio will even bundle together the package path so that you can
work with the files without having to drill down through the folders that make up your package.
3. Res Folder:
• It contains folders that help us to separate and sort the resources of our application. Resources
basically mean all the needed files except the source code.
• For example, while developing an app, we need to include resource files such as the app-logo, photos,
sounds, videos or animations. Each file type should be added to its own folder to comply with the
Android development standards.
• When we use Android Studio to create a new application, some folders will be automatically
generated for we. However, these folders are not the only ones we can use in our project. The
following are the folders that can be used inside of the res folder:
(i) Drawable Folder:
• The drawable folder contains graphics that can be drawn to the screen. For example, images files
(png, jpg and gif), various XML (clip drawable, insert drawable, layer list, level list, scale drawable,
shape draggable, state list, transition drawable), and predetermined frame animations can be placed
here:
(a) Bitmap File:
Android supports bitmap files in three formats: .png (preferred), .jpg (acceptable), .gif
(discouraged).
(b) Nine-Patch File:
A PNG nine-patch file with stretchable regions to allow image resizing based on content.
(c) Layer List:
An XML file that contains an array made up of other drawables.
(d) State List:
An XML file that is used for images that have multiple or different states of appearance.
(e) Level List:
An XML file that is used to display other drawables that can be accessed based on the level
requested through setImageLevel().
(f) Transition Drawable:
An XML file that contains a drawable that can be transitioned between two items.
(g) Inset Drawable:
An XML file that is used to place one drawable inside the bounds of another drawable.
(h) Clip Drawable:
Mobile Application Development 3.8 UI Components and Layouts

An XML file consisting of points that is used in conjunction with another drawable to create a
clipped objected.
(i) Scale Drawable:
An XML file that contains a drawable that changes the dimension value of another drawable
based on its current value.
(j) Shape Drawable:
An XML file that contains the values of geometric shape, color, size, and similar attributes.
(ii) Layout Folder:
• The layout folder contains XML files used for your layouts. These file are used to set up the layout for
your Activity and is used for basic alignment of your layouts, components, widgets, and similar
resources that are used for the UI of your application.
• activity_main.xml is automatically created in this folder by Android Studio. Layout folder may have
multiple layout folders to handle different devices. This can be helpful when working with layouts
that need to be adjusted for devices with more or less screen space available.
(iii) Mipmap Folder:
• The mipmap folder contains the launcher icon files for the app. A launcher icon is a graphic that
represents your app to users. The mipmap folder was introduced in Android 4.3.
(iv) Values Folder:
• The values folder contains XML files that contain simple values, such as strings, integers, and colors.
The values folder is used to keep track of the values we will be using in our application.
• To create applications with an easier maintenance cycle, it is highly recommended to no longer
hard-code values into our code. Instead, place values in XML files inside of the values folder.
• When we create a new project with Android Studio, the following XML files will be generated
automatically namely, colors.xml, strings.xml and styles.xml.
(v) Other Folders:
• Not all folders may be shown for our resources but we can create other folders for other resources in
our application.
• Following list describes each folder name as well as what should be stored in that folder.
(a) animator
XML files that define property animations.
(b) anim
XML files that define tween animations.
(c) color
XML files that define a state list of colors.
(d) menu
XML files that define application menus.
(e) raw
Any files to save in their raw form. For example, sound and video files are placed in the raw
folder.
(f) xml
Any XML files that can be read at runtime.
(g) font
Font files with extensions such as ttf, otf, or ttc, or XML files.
Gradle Scripts:
• APK files are built using the gradle build system, which is integrated in the Android Studio. When we
start an app, the gradle build scripts are automatically created. If we have special requirements for
our project, we can specify these requirements here.
Mobile Application Development 3.9 UI Components and Layouts

Fig. 3.12

• The gradle scripts folder contains the scripts used to build the app are configuration files, properties
files, and setting files.
3.3 UNDERSTANDING THE COMPONENTS OF A SCREEN
• An activity provides the window in which the app draws its UI. This window typically fills the screen,
but may be smaller than the screen and float on top of other windows.
• Generally, one activity implements one screen in an app. For instance, one of an app’s activities may
implement a Preferences screen, while another activity implements a Select Photo screen.
• Activities serve as the entry point for a user's interaction with an app and are also central to how a
user navigates within an app, (as with the Back button) or between apps, (as with the Recents
button).

Fig. 3.13: Components of Android Screen

• An activity represents a single screen with a User Interface (UI), 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.
Mobile Application Development 3.10 UI Components and Layouts

• An Activity displays the user interface of our application, which may contain widgets like buttons,
image buttons, text boxes, labels etc. Typically we define your UI using XML file (for example the
activity_main.xml file located in the res then inside a folder called layout), which may look like this:

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


<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/ap
k/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<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" />

</android.support.constraint.ConstraintLayout>

• During the runtime, we can load the XML UI in the onCreate() event handler in our Activity class,
using the setCotentview() method of the Activity class:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

• During compilation time , each element in the XML file is compiled into its equivalent Android GUI
class, with an attribute represents by methods. The android system then creates the user
interface(UI) of the Activity when it is loaded.
3.4 FUNDAMENTALS OF UI DESIGN
• Every item in a user interfaces is a subclass of the Android View class which is present inside the
package(android.view). The android SDK provides a set of pre-built views that can be used to
construct the user interface.
• Typical examples include items such as Button, ImageButton, checkbox, ProgressBar and Tectview
classes.
1. Views:
• The basic building block for user interface in Android is a View, which is created from the View class
and occupies a rectangular area on the screen and is responsible for drawing and event handling.
• Views are the base class for all visual interface elements (commonly known as controls or widgets).
All user interface UI controls, including the layout classes, are derived from View.
• A View is an object/widget that draws something on the sreen by the help of user interact.
• Examples of widgets are buttons, text boxes, labels etc.
2. View Groups:
Mobile Application Development 3.11 UI Components and Layouts

• The ViewGroup is a subclass of View and provides invisible container that hold other Views or other
ViewGroups and define their layout properties.
• View groups are extensions of the View class that can contain multiple child Views. In order to
Extend the ViewGroup class to create compound controls made up of interconnected child views.
• A ViewGroup provides the layout in which we can order the appearance and sequence of views.
Examples of ViewGroup are FrmaeLayout, LineourLayout etc.
3. Fragments:
• Fragments represents a portion of user interface in an Activity. Fragments, introduced in Android
3.0 which uses API level 11, are used to encapsulate portions of your UI. This encapsulation makes
fragments particularly useful when optimizing our UI layouts for different screen sizes and creating
reusable user interface (UI) elements.
• Each Fragment includes its own user interface (UI) layout and receives the related input events but is
tightly bound to the activity into which each must be embedded. Fragments are similar to UI view
controller in iPhone development.
4. Activities:
• Activities dictate the UI and handle the user interaction to the smart phone screen. Activities
represent a single screen that user interact.
• Activities are the Android equivalent of Forms in traditional windows desktop development. To
display a UI we assign a View (Usually a layout or Fragment) to an Activity
3.5 UI LAYOUTS
• A layout defines the structure for a User Interface in the application. There are number of Layouts
provided by Android which we will use in almost all the Android applications to provide different
view, look and feel. Each layout has a set of attributes which define the visual properties of that
layout. There are few common attributes among all the layouts and their are other attributes which
are specific to that layout.
• Layouts in Android are very important for GUI based apps.The Android SDK includes the following
layout views that may be used within an Android user interface design.
1. LinearLayout is a view group that aligns all children in a single direction, vertically or
horizontally.
2. RelativeLayout is a view group that displays child views in relative positions.
3. TableLayout is a view that groups views into rows and columns.
4. AbsoluteLayout enables you to specify the exact location of its children.
5. FrameLayout is a placeholder on screen that you can use to display a single view.
6. ListView is a view group that displays a list of scrollable items.
7. GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.
3.3.1 LinearLayout
• Android LinearLayout is a view group that aligns all children in either vertically or horizontally.
Linear layout in Android allow us to arrange components horizontally in a single column or
vertically in a single row.
• Vertically or horizontally direction depends on attribute android: orientation.
• Linear layout is simple and easy to use, it creates a scroll bar if the length of the window exceeds the
length of the screen.
• Linear Layout are one of the simplest and common type of layouts used by Android developers to
keep controls within their interfaces. The linear layout works as much as its name implies, it
organizes the controls either a vertical or horizontal pattern.
Mobile Application Development 3.12 UI Components and Layouts

• When the layout’s orientation is set to vertical, all child controls within organized in a single
column, and when the layout’s orientation is set to horizontal, all child controls within in single row.

Fig. 3.14: Linear Layout

• Linear layouts can be defined within XML layout resourses or programmatically in the applications
java code. This linear layout’s orientation is set to be vertical, causing each of the view controls to
display in single column from top to bottom. Each TextView control has its text attributes set to a
color, with the same color set as the background for the control; each control is stretched to the
width of the screen by setting the controls layout_width attribute to fill_parent. Child views can be
arranged either horizontally or vertically.
• We have seen that android mobile screen size are different from device to device, some mobile sizes
are same. Suppose we are developing one application which contains a text field and button, when
the application changes from one mobile to the other mobile then the problem is regarding the
layout of the component. It happens because the size of screen varies.
Attributes of linear layout:
1. Id: Unique identifier of layout.
2. Orientation: Attribute to set linear layout orientation as vertical or horizontal.
3. Layout_Weight: This attribute assigns “importance” value at each component.
4. Gravity: This attribute shows object position in x-y plan such as center, right, top, bottom and
left.
5. Weight_sum: This attribute defines the maximum weighted sum.
6. Divider: draw able to use as a vertical divider between buttons.
Constructors of linear layout:
• LinearLayout(Context context)
• LinearLayout(Context context, AttributeSetattrs)
• LinearLayout(Context context, AttributeSetattrs, intstyleAttribute)
• LinearLayout(Context context, AttributeSetattrs, intstyleAttribute, intstyleRes)
Example:
• Linear layout looks different if the attributes values are set different for two linear layouts, such as
vertical linear layout or horizontal linear layout.
• Following example shows vertical linear layout. Here is the activity_linear_vertical.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutandroid:layout_width="368dp"
android:layout_height="495dp"
xmlns:tools="http://schemas.android.com/tools"
Mobile Application Development 3.13 UI Components and Layouts

android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:id="@+id/button6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button2" />

<Button
android:id="@+id/button7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button3" />
<Button
android:id="@+id/button8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button4" />
</LinearLayout>
Output:

• Here is another example which shows horizontal linear layout. Below is the code for
activity_linear_horizontal.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutandroid:layout_width="368dp"
android:layout_height="495dp"
Mobile Application Development 3.14 UI Components and Layouts

xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button4" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button3" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button2" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1" />
</LinearLayout>
Output:
Mobile Application Development 3.15 UI Components and Layouts

3.3.2 Absolute Layout


• AbsoluteLayout is based on the simple idea of placing each control at an absolute position. We
specify the exact x and y coordinates on the screen for each control. This is not recommended for
most UI development (in fact AbsoluteLayout is currently deprecated) since absolutely positioning
every element on the screen makes an inflexible UI that is much more difficult to maintain.

Fig. 3.15: Absolute Layout


• An Absolute Layout lets you specify exact locations (x/y coordinates) of its children. Absolute layouts
are less flexible and harder to maintain than other types of layouts without absolute positioning.
AbsoluteLayout is based on the simple idea of placing each control at an absolute position.
• We specify for the exact x and y corodinates on the screen for every control. So this recommended
for most UI development (in fact Absolute Layout is currentaly deprecated)since absolute
positioning of every element on the screen makes an inflexible UI that is much more difficult to
maintain.
• Consider what happens if a control needs to be added to the user interface UI, we would have to
change the position of every single element that is shifted by the new control. This allows child views
to be positioned at specified X and Y coordinates within the containing layout view.
Example: In main.xml add following code:

<AbsoluteLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_x="110px"
android:layout_y="110px"
android:text="User Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:layout_x="250px"
android:layout_y="80px"
android:width="100px"
android:layout_width="200dp"
android:layout_height="wrap_content" />
<TextView
android:layout_x="110px"
Mobile Application Development 3.16 UI Components and Layouts

android:layout_y="200px"
android:text="Password"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:layout_x="250px"
android:layout_y="150px"
android:width="100px"
android:layout_width="200dp"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Log In"
android:layout_x="300px"
android:layout_y="300px"/>
</AbsoluteLayout>

• Now Open java → package → MainActivity.java and paste the below code.

packageexample.abhiandriod.absolytelayoutexample;
import android.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.view.Menu;
importandroid.view.MenuItem;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
publicbooleanonCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
publicbooleanonOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspectionSimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
returnsuper.onOptionsItemSelected(item);
}
Mobile Application Development 3.17 UI Components and Layouts

Output:

3.3.3 Frame Layout


• Frame Layout is designed to block out an area on the screen to display a single item. Generally,
FrameLayout should be used to hold a single child view, because it can be difficult to organize child
views in a way that's scalable to different screen sizes without the children overlapping each other.
• Frame layouts are one of the simplest layout types used to organize controls within the user
interface of an Android application. The purpose of FrameLayout is to allocate an area of screen.
FrameLayoue in android is for displaying a single view.

Fig. 3.16: Frame Layout


• In the above image, the black frame is the frame layout and in colors, you can find four different
components. The gravity settings of each of those components look like this:
o Component 1 – Top Left.
o Component 2 – Top Right.
o Component 3 – Bottom Left.
o Component 4 – Bottom Right.
• We can, however, add multiple children to a FrameLayout and control their position within the
FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute.
Mobile Application Development 3.18 UI Components and Layouts

Fig. 3.17: Frame Layout


• Frame layouts are one of the most efficient types of layouts used by Android developers to organize
view controls. They are used less often than some other layouts, simply because they are generally
used to display only one view, or views which overlap.
• The frame layout is often used as a container layout, as it generally only has a single child view
(often another layout, used to organize more than one view).
XML attribute of Frame Layout:
1. android:id: This attribute will give the unique identity to the framelayout. When you want to access
the framelayout from the JAVA class, this id will give us the reference via findViewById() method.
• Value of this attribute should be unique across the whole android app to reduce the complexity.
For example,
<FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frame"
android:layout_width="200dp"
android:layout_height="300dp"
android:foreground="@color/colorAccent"
tools:context=".MainActivity">
2. android:foreground: This attribute allows us to draw to certain view on the whole framelayout.
• The value of this property can be a color, a drawable file or a simple image.
• Possible color values are “#rgb”, “#argb”, “#rrggbb”, or “#aarrggbb” according to various RGB
values.
• Now make a new project in android studio. Do not touch the MainActivity.java class. Keep it as it is.
Add the below source code in activity_main.xml file.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frame"
android:layout_width="200dp"
android:layout_height="300dp"
android:foreground="@color/colorAccent"
tools:context=".MainActivity">
Mobile Application Development 3.19 UI Components and Layouts

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="90dp"
android:text="Button"/>
<TextView
android:layout_width="100dp"
android:layout_height="50dp"
android:textSize="20sp"
android:background="@color/colorPrimary"
android:textColor="#fff"
android:text="I am TextView" />
</FrameLayout>
3. android:visibility: We can apply this attribute to any child of the framelayout.
• Possible values for visibility are visible, invisible and gone.
o Visible means that the view is present and we can also see it.
o Invisible means that the view is present and we can not see it.
o Gone means that view is not present and so we can not see it.
4. android:measureAllChildren: This property defines whether to measure the all the children
including those who are with “Gone” visibility state or to measure only those who have “visible” or
“invisible” state.
• This property can have “True” or “False” value.
• If true then it will include the child with gone visibility otherwise not.
Methods of FrameLayout
1. generateLayoutParams(AttributeSet attrs): It Returns a new set of layout parameters based on the
supplied attributes set.
2. getAccessibilityClassName(): Return the class name of this object to be used for accessibility
purposes.
3. getMeasureAllChildren(): Determines whether all children, or just those in the VISIBLE or INVISIBLE
state, are considered when measuring. It will return boolean value. (True or False)
• If it returns false then compiler will consider only VISIBLE or INVISIBLE state of children of
framelayout.
• For true, it will consider VISIBLE, INVISIBLE and GONE state of children of framelayout.
4. setForegroundGravity(intforegroundGravity): Describes how the foreground is positioned.
5. setMeasureAllChildren(booleanmeasureAll): Sets whether to consider all children, or just those in
the VISIBLE or INVISIBLE state, when measuring.
6. shouldDelayChildPressedState(): Return true if the pressed state should be delayed for children or
descendants of this ViewGroup.
7. generateDefaultLayoutParams(): Returns a set of layout parameters with a width of
ViewGroup.LayoutParams.MATCH_PARENT, and a height of ViewGroup.LayoutParams. MATCH_
PARENT.
8. generateLayoutParams(ViewGroup.LayoutParams lp): Returns a safe set of layout parameters
based on the supplied layout params.
9. onLayout(boolean changed, int left, int top, int right, int bottom): Called from layout when this
view should assign a size and position to each of its children.
Mobile Application Development 3.20 UI Components and Layouts

10. onMeasure(intwidthMeasureSpec, intheightMeasureSpec): Measure the view and its content to


determine the measured width and the measured height. This method is invoked by measure (int,
int) and should be overridden by sub classes to provide accurate and efficient measurement of their
contents.
Examples of FrameLayout:
Code for MainActivity.java
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
In your activity_main.xml file,
<?xml version="1.0" encoding="utf-8"?>
<FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/framelayout"
android:layout_width="200dp"
android:layout_height="300dp"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="90dp"
android:layout_marginLeft="20dp"
android:text="Button"/>
<TextView
android:layout_width="100dp"
android:layout_height="50dp"
android:textSize="20sp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:background="@color/colorPrimary"
android:textColor="#fff"
android:text="I am TextView" />
</FrameLayout>
Output:
Mobile Application Development 3.21 UI Components and Layouts

Example 2:
Again, do not change anything in the MainActivity.java file.
Code for activity_main.xml is like the below
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"&gt;
&lt;ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="@mipmap/ic_launcher_round"/&gt;
&lt;Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="0dp"
android:text="Button"/&gt;
&lt;TextView
android:layout_width="100dp"
android:layout_height="50dp"
android:textSize="20sp"
android:layout_gravity="center"
android:background="@color/colorPrimary"
android:textColor="#fff"
android:text="I am TextView" /&gt;
&lt;/FrameLayout&gt;
Output:
Mobile Application Development 3.22 UI Components and Layouts

3.5.4 RelativeLayout
• Relativelayout as the name suggests, shows position of components
relative to each other. The position can be specified with respect to
consecutive elements or to the parent component.
• Relativelayout is most flexible layout provided by Android. It lets us
to position elements on the screen. By default, it sets all
components at the top left of the layout.
• Android RelativeLayout enables us to specify how child views are
positioned relative to each other. The position of each view can be
specified as relative to sibling elements or relative to the parent.
• RelativeLayout is a view group that displays child views in relative
positions. The position of each view can be specified as relative to
sibling elements (such as to the left-of or below another view) or in
positions relative to the parent RelativeLayout area (such as aligned Fig. 3.8: RelativeLayout
to the bottom, left or center).
• RealativeLayout is probably the most powerful and flexible of the layout managers, which allows
child views to be positioned relative both to each other and the containing layout view through the
specification of alignments and margins on child views.
• For instance, child View X may be configured to be positioned in the vertical and horizontal center of
the containing Relative Layout view. View Y, or on other hand, might also be configured to be
centered horizontally within the layout view, but positioned 30 pixels on top of the top edge of View
X, thereby making the vertical position relative to that of View X.
• The RelativeLayout manager can be of particular use when designing a user interface that must
work on avariety of screen sizes and orientations.
• RelativeLayout lays out elements based on their relationships with each other, and with the parent
container. This is possibly the most complicated layout, and we require several properties to actually
get the layout we want.
• These properties will layout elements comparative to the parent container.
Sr.
Properties Description
No.
1. android:layout_alignParentBottom It places the bottom of the element on the bottom of the
Mobile Application Development 3.23 UI Components and Layouts

container.
2. android:layout_alignParentLeft It places the left of the element on the left side of the
container.
3. android:layout_alignParentRight It places the right of the element on the right ide of the
container.
4. android:layout_alignParentTop It places the element at the top of the container.
5. android:layout_centerHorizontal It centers the element horizontally within its parent
container.
6. android:layout_centerInParent It centers the element both horizontally and vertically
within its container.
7. android:layout_centerVertical It centers the elements vertically within its parent
container.
• These properties allow us to layout elements relative to other elements on screen. The value for each
element is the id of the element we are using to layout the new element.
• Every element that is use dthis way must have an ID defined using android:id=”@a+id/viewname”
where viewname is replaced with the desired id. We use “@id/viewname” to refer to an element by
its id.
Sr.
Properties Description
No.
1. android:layout_above It places the element above the specified element.
2. android:layout_below It places the element below the specified element.
3. android:layout_toLeftOf It places the element to the left of the specified element.
4. android:layout_toRightOf It places the element to the right of the specified
element.
5. android:layout_alignBaseline It aligns baseline of the new element with the baseline of
the specified element
6. android:layout_alignBottom It aligns bottom of the new element with the bottom of
the specified element
7. android:layout_alignLeft It aligns left edge of the new element with the left edge
of the specified element.
8. android:layout_alignRight It aligns right edge of the new element with the right
edge of the specified element.
9. android:layout_alignTop It aligns top of the new element with the top of the
specified element
Example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/btnButton1"
Mobile Application Development 3.24 UI Components and Layouts

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"/>
<Button
android:id="@+id/btnButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
android:layout_toRightOf="@+id/btnButton1"/>
<Button
android:id="@+id/btnButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 3"
android:layout_below="@+id/btnButton1"/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnButton3"
android:layout_marginTop="94dp"
android:text="User :"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView1"
android:layout_toRightOf="@+id/btnButton3" />
<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@+id/editText1"
android:text="Submit" />
</RelativeLayout>
Output:
Mobile Application Development 3.25 UI Components and Layouts

3.5.5 TableLayout
• Android TableLayout going to be arranged groups of views into rows and columns. You will use the
<TableRow> element to build a row in the table. Each row has zero or more cells; each cell can hold
one View object.
• TableLayout Arranges child views into a grid format of columns and rows. Each row within a table is
represented by a TableRow object child, which contains a view object for each cell.
• TableLayout organizes content into columns and rows. The rows are defined in the layout XML code,
and the columns are determined automatically by Android, which is done by creating at least one
column for each element. So, for example, if we have a row with two elements and a row with five
elements then we would have a layout with two rows and five columns.
• We can specify that an element should occupy more than one column using androidlayout_span. so
if we have a row with two elements and each element has android: layout_span="2" then we will have
at least six columns in our table.
• By default, Android places each element in the first unused column in the row. We can, however,
indicate the column an element should occupy using android:layout column.
• In android, TableLayout is a ViewGroup subclass which is used to display the child View elements in
rows and columns. TableLayout containers do not display border lines for their rows, columns, or
cells.

Fig. 3.19: TableLayout


• A table layout is exactly what you might expect: a grid of made up of rows and columns, where a cell
can display a view control. From a user interface design perspective, a TableLayout is comprised of
Mobile Application Development 3.26 UI Components and Layouts

TableRow controls—one for each row in your table. The contents of a TableRow are simply the view
controls that will go in each “cell” of the table grid.
• The appearance of a TableLayout is governed by several additional rules. First, the number of
columns of the entire table matches the number of columns in the row with the most columns.
Second, the width of each column is defined as the width of the widest content in the column. The
TableLayout’s child rows and cells layout_width attributes are always MATCH_PARENT -- although
they can be put in an XML file, the actual value can't be overridden.
• The TableLayout’slayout_height of a cell can be defined, but a TableRow attribute for layout_height is
always WRAP_CONTENT.
• Cells can span columns, but not rows. This is done through the layout_span attribute of the child
view of a TableRow. A cell is a single child view within a TableRow. If you want a more complex cell
with multiple views, use a layout view to encapsulate the other views.
• That said, some rules can be modified. Columns can be marked as stretchable, which means that the
width can expand to the size of the parent container. Columns can also be marked as shrinkable,
which means that they can be reduced in width so the whole row will fit in the space provided by the
parent container. We can also collapse an entire column.
Example:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="*"
android:stretchColumns="*">
<TableRow
android:id="@+id/tableRow4"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:gravity="center_horizontal">
<TextView
android:id="@+id/textView9"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:typeface="serif"
android:textSize="18dp"
android:text="Weather Table"
android:gravity="center"
android:layout_span="6"></TextView>
</TableRow>
<TableRow
android:id="@+id/tableRow1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="@+id/TextView04"
android:text=""></TextView>
Mobile Application Development 3.27 UI Components and Layouts

<TextView
android:id="@+id/TextView04"
android:text="Feb 7"
android:textStyle="bold"
android:typeface="serif"></TextView>
<TextView
android:id="@+id/TextView03"
android:text="Feb 8"
android:textStyle="bold"
android:typeface="serif"></TextView>
<TextView
android:id="@+id/TextView02"
android:text="Feb 9"
android:textStyle="bold"
android:typeface="serif"></TextView>
<TextView
android:id="@+id/TextView01"
android:text="Feb 10"
android:textStyle="bold"
android:typeface="serif"></TextView>
<TextView
android:text="Feb 11"
android:id="@+id/textView1"
android:textStyle="bold"
android:typeface="serif"></TextView>
</TableRow>
<TableRow
android:layout_height="wrap_content"
android:id="@+id/tableRow2"
android:layout_width="match_parent">
<TextView
android:text="Day High"
android:id="@+id/textView2"
android:textStyle="bold"></TextView>
<TextView
android:id="@+id/textView3"
android:text="28°F"
android:gravity="center_horizontal"></TextView>
<TextView
android:text="26°F"
android:id="@+id/textView4"
android:gravity="center_horizontal"></TextView>
<TextView
android:text="23°F"
android:id="@+id/textView5"
android:gravity="center_horizontal"></TextView>
<TextView
android:text="17°F"
android:id="@+id/textView6"
android:gravity="center_horizontal"></TextView>
Mobile Application Development 3.28 UI Components and Layouts

<TextView
android:text="19°F"
android:id="@+id/textView7"
android:gravity="center_horizontal"></TextView>
</TableRow>
<TableRow
android:layout_height="wrap_content"
android:id="@+id/tableRow2"
android:layout_width="match_parent">
<TextView
android:text="Day Low"
android:id="@+id/textView2"
android:textStyle="bold"></TextView>
<TextView
android:text="15°F"
android:id="@+id/textView3"
android:gravity="center_horizontal"></TextView>
<TextView
android:text="14°F"
android:id="@+id/textView4"
android:gravity="center_horizontal"></TextView>
<TextView
android:text="3°F"
android:id="@+id/textView5"
android:gravity="center_horizontal"></TextView>
<TextView
android:text="5°F"
android:id="@+id/textView6"
android:gravity="center_horizontal"></TextView>
<TextView
android:text="6°F"
android:id="@+id/textView7"
android:gravity="center_horizontal"></TextView>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:gravity="center">
<TextView
android:id="@+id/textView8"
android:text="Conditions"
android:textStyle="bold"></TextView>
<ImageView
android:id="@+id/imageView1"
android:src="@drawable/hot"></ImageView>
<ImageView
android:id="@+id/imageView2"
android:src="@drawable/pt_cloud"></ImageView>
<ImageView
Mobile Application Development 3.29 UI Components and Layouts

android:id="@+id/imageView3"
android:src="@drawable/snow"></ImageView>
<ImageView
android:id="@+id/imageView4"
android:src="@drawable/lt_snow"></ImageView>
<ImageView
android:id="@+id/imageView5"
android:src="@drawable/pt_sun"></ImageView>
</TableRow>
</TableLayout>
Output:

Practice Questions
1. What is meant by control flow?
2. Explain screen elements for Android.
3. What is directory?
4. Describe directory structure in detail.
5. Explain the term fundamentals of UI design in detail.
6. What is meant by layout?
7. Explain linearlayout with example.
8. Describe frameLayout with example
9. Explain the following terms:
(i) TableLayout (ii) AbsoluteLayout

You might also like