UNIT III – UI COMPONENTS AND LAYOUTS
Control Flow –
Create a new project in Android Studio.
Set up an AVD or connect a physical device.
Run the app on the emulator or phone.
Modify the code and UI to build features.
Test and debug using the Logcat and Debugger.
1. Creating a New Project in Android Studio
1. Open Android Studio
o Launch Android Studio on your computer.
2. Start a New Project
o Click "Start a new Android Studio project" on the welcome screen.
3. Choose Project Template
o Select "Empty Activity" .
o Click Next.
4. Configure Your Project
o Name: Enter your app name.
o Package Name: It should be unique (e.g., com.example.myapp).
o Save Location: Choose where to save the project.
o Language: Select Java or Kotlin as required.
o Minimum SDK: Choose an appropriate version (e.g., API 24: Android 7.0).
o Click Finish.
5. Wait for Project Setup
o Android Studio will build the project and set up Gradle.
2. Understanding Project Structure
MainActivity.java → Entry point of the app (Handles user interaction).
activity_main.xml → UI layout file (Contains buttons, text fields, etc.).
AndroidManifest.xml → Contains permissions, app metadata, and activity
declarations.
res Folder → Stores UI resources like images, layouts, and strings.
Gradle Scripts → Manages dependencies and build settings.
3. Setting Up an Android Virtual Device (AVD)
An AVD (Android Emulator) is used to test your app without a physical device.
Creating an Emulator
1. Open AVD Manager
o In Android Studio, go to Tools > Device Manager.
o Click Create Device.
2. Select a Device
o Choose a phone model (e.g., Pixel 4).
o Click Next.
3. Choose System Image
o Download the latest recommended system image
o Click Next.
4. Configure Emulator Settings
o Keep default settings.
o Click Finish.
5. Start the Emulator
o In the Device Manager, click the Play button to launch the emulator.
4. Running the App on Emulator
1. Ensure AVD is Running
o Start the virtual device if it’s not already running.
2. Click Run in Android Studio
o Select your AVD from the list.
o Click Run to install and launch the app on the emulator.
3. App Launches on Emulator
o You will see the default app UI on the screen.
Directory Structure –
The directory structure of an Android Studio
project typically follows a well-organized
hierarchy that separates different types of files
(source code, resources, and configuration files).
Here’s a breakdown of the common directory
structure:
1. Root Directory
At the root of the Android project, you’ll find
several essential configuration files and folders:
build.gradle (Project-level): Defines project-
wide build configurations (dependencies,
repositories).
settings.gradle: Contains the list of modules
for the project.
gradle.properties: Used for project-specific
Gradle settings.
local.properties: Stores local settings (e.g.,
Android SDK path).
2. App Module Directory (app/)
The main module of your Android project is usually
located in the app/ directory. This folder contains
subfolders and files crucial for building your app:
src/: Contains your source code, resources, and
manifest files.
o main/: This is where the majority of your
code and resources are stored.
java/: Contains Java (or Kotlin) source
files, including Activities, Fragments,
and other classes.
com/example/yourapp/: Your
application's package structure.
MainActivity.java: Main entry
point for the app.
OtherActivity.java: Additional
activities in your app.
res/: Contains all the resources for
your app (layouts, images, strings,
etc.).
layout/: XML files defining the
layout of your app’s
activities/fragments.
drawable/: Images and drawable
resources.
values/: XML files containing
values like strings, colors,
styles, and dimensions.
strings.xml: Text strings used
in the app.
colors.xml: Color values.
styles.xml: Style definitions.
AndroidManifest.xml: Declares
components like activities, services,
permissions, etc., for the app.
assets/: Contains raw files (e.g.,
fonts, databases, etc.) that you may
need in your app, accessed via
AssetManager.
lib/: Native libraries for your app (if
using JNI/NDK).
jniLibs/: Native code files (shared
libraries) for Android (e.g., .so
files).
build/: Automatically generated by Gradle.
Contains compiled resources, APKs, and other
build-related files.
proguard-rules.pro: Used for ProGuard (or R8)
rules to shrink and obfuscate the code.
3. Gradle Wrapper
gradle/: Contains Gradle wrapper files that
make the project compatible with specific
Gradle versions.
o wrapper/: Contains files like gradle-
wrapper.jar and gradle-wrapper.properties,
which allow Gradle to be downloaded
automatically if not already present.
Components of a Screen –
the components of the screen (i.e., the user interface elements that
make up the app’s layout) are commonly known as UI components or
views. These components allow you to create interactive and visually
appealing screens for your users. They are defined using XML for
layout files, or can also be created dynamically in Java or Kotlin code.
1. TextView
2. EditText
3. Button
4. ImageView
5. Layouts / UI Design
6. ProgressBar
7. Toolbar
Fundamental UI Design -
A UI is defined in an xml file. During compilation, each element in
the XML is compiled into equivalent Android GUI class with
attributes represented by methods.
Principles of Good UI Design:
Simplicity: Keep the design clean and uncluttered.
Consistency: Maintain a consistent look and feel throughout
the app.
Feedback: Provide immediate feedback to user actions.
Responsiveness: Ensure the app is responsive and fast.
Aesthetics: Make the app visually appealing.
UI Components:
Views: A View is an object / widget that draws something on
the screen by the help of user interact. Basic building blocks
like TextView, Button, ImageView, etc. One or more views
can be grouped together into one Group View.
View Groups are extension of the view class that can contain
multiple child views
The View Group class is also extended to provide the layout
managers that help us to control layout within our Activities.
Layouts: Containers for organizing views, such as
LinearLayout, RelativeLayout, ConstraintLayout.
Widgets: Pre-built UI components like Spinners,
ProgressBars, etc. Widgets are buttons , text boxes , labels etc
Design Patterns:
Activity: Represents a single screen with a user interface. An
activity consists of views. Views are base class for all visual
interface elements . All UI control elements are derived from
View.
Fragment: A portion of the user interface or behavior that
enables a new screen layout.
Linear Layout -
Linear Layout is a view group that aligns all children in a single
direction, vertically or horizontally.
It is useful for creating simple and clean layouts.
When layout’s orientation is set to vertical , all child controls are
organized in a single column.
When layout’s orientation is set to horizontal , all child controls
are organized in a single row.
Linear codes can be defined in XML layout resources or
programmatically in the applications Java code.
To stretch the content throughout the screen , we need to set
width and height to match parent.
As there are different sizes of screen we can use match parent
and wrap content accordingly.
Match Parent (match_parent) - The component wants to display
as big as its parent and fill in the remaining spaces.
Wrap Content (wrap_content) – The component want to display
as big enough to enclose its content only.
Attributes:
Attributes Description
android:orientation Defines the orientation
(horizontal or vertical)
android:layout_height Define the height of the Linear
Layout.
android:layout_width Define the width of the Linear
Layout.
android:layout_weight Distributes extra space among
child views.
android:gravity Aligns the child views within the
Linear Layout.
android:layout_margin Space outside the view.
android:padding Space inside the view.
Use Cases:
1. Simple Layouts: For simple, linear arrangements of views.
2. Equal Width/Height: When you want to distribute space
equally among child views.
3. Horizontal/Vertical Lists: Creating lists.
Advantages:
Simplicity: Easy to understand and use.
Performance: Generally faster than more complex layouts.
Disadvantages :
Flexibility: Can become complex for more intricate designs.
Nested Layouts: Can lead to performance issues.
XML Layout -
Absolute Layout –
An absolute layout is a type of layout manager that allows you
to specify the exact location of components (such as buttons,
labels, text fields, etc.) on a container.
This layout manager is used to create custom user interfaces
where components are positioned at specific coordinates relative
to the container's top-left corner.
Components are added to the container using absolute
coordinates, by specifying their exact x and y positions and
dimensions.
Absolute layouts are less flexible and harder to maintain across
different screen sizes and resolutions. This is why they have
been deprecated in Android development.
This layout is not responsive to changes in window size.
Can be difficult to manage for complex UIs.
Attributes –
Attributes Description
android:layout_x Specifies the X coordinate
(horizontal position) of the view
within the parent layout.
android:layout_y Specifies the Y coordinate
(vertical position) of the view
within the parent layout.
android:layout_height Define the height of the Layout.
android:layout_width Define the width of the Layout.
android:layout_weight Distributes extra space among
child views.
android:gravity Aligns the child views within the
Linear Layout.
android:layout_margin Specifies the space outside the
view.
android:padding Specifies the space inside the
view.
android:visibility Controls the visibility of the
view.
Use Cases:
Suitable for specific graphic designs, custom UI layouts,
or when exact positioning is critical.
Often used in legacy applications or specific scenarios
where absolute control is necessary.
Advantage:
Precise control over component placement.
Flexible and powerful layout manager.
Supports chains, barriers, and groups for more complex layouts.
Disadvantage:
Can be complex to learn and use for beginners.
May have performance overhead for very complex layouts.
Frame Layout –
Frame Layout is a view group that displays child elements in a stack,
with each child element occupying the same space and layered on top
of each other. It's one of the simplest layout types available in Android
and is often used when you want to overlap views or when you have a
small number of items that you want to position in a specific way.
Each child in a Frame Layout is drawn in a simple stack, with the
most recently added child on top.
Attributes –
Attribute Description
android:layout_width
Specifies the width of the FrameLayout (e.g.,
match_parent, wrap_content).
android:layout_height Specifies the height of the FrameLayout.
android:foreground Defines a drawable to be displayed on top of the layout.
android:foregroundGravity
Controls the gravity of the foreground drawable (e.g.,
center, top, bottom).
Attribute Description
android:measureAllChildren
If true, all child views are measured, even if they are
GONE. Default is false.
Attribute Description
android:layout_gravity
Specifies how the child view is positioned inside the
FrameLayout (e.g., top, center, bottom).
android:layout_margin Adds margin around the child view.
android:visibility Controls the visibility (visible, invisible, gone).
Use Cases:
Display a progress bar or spinner on top of other content
while loading data.
Overlay controls (e.g., play, pause, volume) on top of a
video or media player.
Create a splash screen by overlaying a logo or animation
on top of a background.
Advantage:
Used for layering views, such as floating buttons, overlays, or
backgrounds with text on top.
If there’s only one child, it takes up minimal memory and
improves performance.
It is the preferred layout for Fragment containers in activities.
Disadvantage:
Since all child views are stacked, it can be difficult to manage
multiple elements properly.
Unlike LinearLayout, FrameLayout doesn’t provide flexible
positioning.
If multiple views are added, they may overlap in an unwanted
way, requiring additional layout_gravity adjustments.
XML Layout -
Table Layout –
A table layout refers to the arrangement and organization of elements
within a table, that is in the form of Rows and Columns. Each row
within a table is represented by a TableRow, which is a object child
Table Layout is a view group that should be used to contain Table
Row objects. It does not display borders for its child elements.
Each TableRow creates a new row in the table. You can add views
(like TextView, Button, etc.) to each TableRow.
1. TableLayout Attributes
A ribute Descrip on
Specifies which columns should expand to fill available space (e.g.,
android:stretchColumns
"1" for the second column, "*" for all columns).
Specifies which columns can shrink to fit content (e.g., "0,2" for
android:shrinkColumns
the first and third columns).
android:collapseColumns Hides specific columns (e.g., "1" to hide the second column).
android:padding Sets padding around the table.
android:background Sets background color or drawable for the table.
android:layout_width Width of the table (usually match_parent or wrap_content).
android:layout_height Height of the table.
2. TableRow Attributes
A TableRow is used inside TableLayout to define a row.
A ribute Descrip on
android:gravity Aligns content within the row (e.g., "center", "left").
android:background Sets background color or drawable.
android:padding Adds padding inside the row.
Each child inside a TableRow (like TextView, Button, etc.) behaves like a table cell.
Use Cases:
Simple Data Presentation: When you need to display a list of items in
a tabular format, such as a schedule, a price comparison chart, or a list
of settings, TableLayout can help you align the data in a clear and
organized manner.
Calendars: Calendar applications can use TableLayout to display days
of the week and dates in a grid format. Each cell can represent a day,
and the layout can be adjusted to fit the number of weeks in a month.
Image Galleries: TableLayout can be used to create a gallery of
images where each row contains a fixed number of images, and the
layout adjusts to fit the screen size and orientation.
Game Boards: Games that require a grid layout, such as chess or tic-
tac-toe, can use TableLayout to manage the board layout and
interactions.
Advantage:
1. Simple Grid Layout: TableLayout provides a straightforward
way to create grid-like layouts without the need for complex
nested layouts.
2. Ease of Use: It's relatively easy to understand and use,
especially for developers familiar with HTML tables.
3. Row and Column Management: It allows for easy
management of rows and columns, making it simple to align
elements in a grid.
4. Stable API: TableLayout has been around for a while, so it's a
stable and well-documented part of the Android framework.
5. Flexibility: It supports both fixed and weighted columns, and
you can specify the number of columns or let them stretch to fit
the screen.
Disadvantage:
1. Performance Issues: Table Layout can be less performant than
other layout managers, especially with a large number of child
views or complex nested tables.
2. Limited Flexibility: It's not as flexible as Relative layout.
3. Nested Complexity: Nesting multiple TableLayouts can lead to
performance degradation and make the layout harder to manage.
4. Scrolling Issues: Scrolling can be problematic with
TableLayout, as it's not designed to handle large or complex
scrollable content.
5. Memory Usage: TableLayout can be memory-intensive, as it
creates a view for each cell, which can lead to increased
memory usage.
XML LAYOUT -
Relative Layout –
Relative Layout is a View Group in Android that allows positioning of
child views relative to each other or to the parent container. It is one
of the most flexible of the layout managers and is useful when you
need to align elements dynamically.
Attributes –
1. Positioning Relative to Parent
Attribute Description
Aligns the view to the top
android:layout_alignParentTop="true"
of the parent.
Aligns the view to the
android:layout_alignParentBottom="true"
bottom of the parent.
Aligns the view to the left
android:layout_alignParentLeft="true"
of the parent.
Aligns the view to the
android:layout_alignParentRight="true"
right of the parent.
Aligns the view to the
android:layout_alignParentStart="true" start (left in LTR, right in
RTL).
Aligns the view to the end
android:layout_alignParentEnd="true" (right in LTR, left in
RTL).
Centers the view both
android:layout_centerInParent="true"
horizontally and vertically.
Centers the view
android:layout_centerHorizontal="true" horizontally within the
parent.
Centers the view vertically
android:layout_centerVertical="true"
within the parent.
2. Positioning Relative to Other Views
Attribute Description
Places the view above
android:layout_above="@id/viewID"
the specified view.
Places the view below
android:layout_below="@id/viewID"
the specified view.
Places the view to the
android:layout_toLeftOf="@id/viewID" left of the specified
view.
Places the view to the
android:layout_toRightOf="@id/viewID" right of the specified
view.
Places the view to the
start (left in LTR, right
android:layout_toStartOf="@id/viewID"
in RTL) of the specified
view.
Places the view to the
end (right in LTR, left in
android:layout_toEndOf="@id/viewID"
RTL) of the specified
view.
Aligns the top edge of
android:layout_alignTop="@id/viewID" the view with another
view.
Aligns the bottom edge
android:layout_alignBottom="@id/viewID" of the view with another
view.
Aligns the left edge of
android:layout_alignLeft="@id/viewID" the view with another
view.
Attribute Description
Aligns the right edge of
android:layout_alignRight="@id/viewID" the view with another
view.
Aligns the start edge of
android:layout_alignStart="@id/viewID" the view with another
view.
Aligns the end edge of
android:layout_alignEnd="@id/viewID" the view with another
view.
Use Cases:
Login screen: Username field above password field, login
button below password field, forgot password link to the right of
the login button.
Profile page: Profile picture at top center, name below picture,
social media icons aligned horizontally below the name.
E-commerce product card: Product image at top, title below
image aligned left, price below title aligned right, "Add to Cart"
button centered below price.
Chat bubble layout: Sender's message aligned right, receiver's
message aligned left, timestamps below each message relative to
the bubble.
Advantage:
Flexible positioning of views relative to each other or the parent.
Reduces need for nested layouts, improving performance in
some cases.
Supports dynamic and responsive UI designs.
Easy to center views or align them with other views.
Allows overlapping views for specific design needs.
Disadvantage:
Higher performance overhead due to two measure passes.
Can become complex and hard to manage in large layouts.
XML code may become less readable with many relative
attributes.
Not ideal for simple UIs where LinearLayout or
ConstraintLayout would suffice.
May lead to unexpected behavior with dynamically added or
removed views.
XML LAYOUT -