Android Unit-3
Android Unit-3
Android Framework: GUI and MVC Architecture, Fragments and Multi-platform development
Creating Widgets: Layouts, Canvas Drawing, Shadows, Gradients
Applications with multiple screens; Handling database in Android: Android Database class,
Using the Database API.
In Android, the Graphical User Interface (GUI) refers to the visual components and interactions
that allow users to interact with their devices or apps. Android's GUI is built using a combination
of layout elements, views, and resources that are arranged and displayed on the screen. Let's break
down the key aspects of how GUI works in Android.
Key Components of Android GUI
1. Activities and Views
o Activity: An Activity is a single screen with a user interface in an Android app. It's a core
component of any app and represents a window where the user interacts with the app. For
example, an Activity could represent a login screen, home screen, or settings screen.
o View: A View is a basic building block of the user interface in Android. Every UI element
(button, text field, image, etc.) is a type of View. Views handle the rendering of content and
user interaction.
2. Layouts
o Layout is a type of ViewGroup that organizes the position and appearance of other
Views on the screen. Android provides several layout types that define how Views should
be arranged:
▪ LinearLayout: Organizes Views in a single direction (either vertically or
horizontally).
▪ RelativeLayout: Positions Views relative to each other based on rules
(e.g., to the left of, below, etc.).
▪ ConstraintLayout: A more flexible and powerful layout that allows you
to define complex relationships between Views.
▪ FrameLayout: A simple layout that stacks Views on top of each other,
often used for fragments.
▪ GridLayout: Organizes Views in a grid of rows and columns.
3. Views and Widgets Android provides a wide variety of widgets that you can use in your
layout:
• TextView: Displays text to the user.
• EditText: A user input field where the user can type text.
• Button: A clickable button.
• ImageView: Displays images.
• CheckBox, RadioButton: Used for boolean selections.
• Spinner: A dropdown list of options.
• ListView or RecyclerView: Used for displaying a list of items that can be
scrolled.
• ProgressBar: A visual indicator of progress (loading).
4. Resources Android separates the visual design from the logic in the app. The resources
include images, icons, layouts, and strings, which are stored in specific directories:
▪ res/layout: Contains XML files defining the structure of your UI (e.g.,
activity_main.xml).
▪ res/drawable: Contains image resources like PNGs and other graphical
assets.
▪ res/values: Contains resources like colors, strings, and dimensions in XML
files (e.g., colors.xml, strings.xml, dimens.xml).
5. Styles and Themes
o Styles: A style is a collection of attributes (such as text size, color, and font) that
can be applied to Views to maintain a consistent look and feel throughout an app.
o Themes: A theme is a collection of styles that apply to the entire app or specific
Activities. Themes help define the overall visual appearance of the app, such as the
colors, fonts, and other visual properties.
6. Event Handling
• Listeners: In Android, user interactions with UI components (like tapping a
button, entering text, etc.) are handled using listeners. For example, a
setOnClickListener method is used to define an action when a button is clicked.
• Touch Events: Android allows handling touch events like gestures (tap, swipe,
pinch) on the screen, which can be captured via the onTouchListener.
7. Fragments
A Fragment is a modular section of an activity's user interface. Fragments enable you to
create flexible, reusable UI components that can be combined and reused across different
Activities or configurations. This is especially useful for designing layouts that work well
on different screen sizes (e.g., tablets and phones).
8. Intents and Navigation
• Intents: In Android, navigation between Activities is handled by Intents. You use
Intents to start a new Activity, pass data between Activities, or perform other tasks
like opening a URL or sending an SMS.
• Navigation Components: With Android Jetpack, the Navigation Component is a
more modern way to handle app navigation, including safe argument passing and
automatic back-stack management.
Example of a Basic Android GUI Layout (XML)
Here’s an example of an XML layout for a simple Android GUI with a button and a text field.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter your name"
android:textSize="18sp" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:inputType="text" />
<Button
android:id="@+id/buttonSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
This layout consists of:
• A TextView that tells the user what to do.
• An EditText for user input.
• A Button for submitting the input.
GUI Design Principles in Android
1. Responsive Design: The design should adapt to different screen sizes and orientations
(portrait/landscape). Android offers several tools like ConstraintLayout, different resource
folders (layout-land, layout-sw600dp), and dp units for consistent sizing across devices.
2. User Experience (UX): Focus on providing a simple, intuitive interface, keeping user
navigation and interaction smooth. Avoid clutter, and ensure that buttons and touch targets
are appropriately sized.
3. Material Design: Google’s design system, Material Design, provides a set of principles
and guidelines for creating a consistent, visually appealing interface. Material Design
emphasizes the use of grids, motion, and components like floating action buttons (FABs),
cards, and navigational drawers.
MVC Model in Android
The Model-View-Controller (MVC) is a software architectural pattern used for developing user
interfaces by separating concerns. In Android development, the MVC model is often used to
organize code in a way that improves maintainability, scalability, and separation of concerns.
1. Model
The Model represents the data or business logic of the application. It is
responsible for
managing the data and operations related to it. The Model doesn't directly
interact with the user interface. Instead, it provides data that the View
displays and handles updates through the Controller.
• Responsibilities:
• Maintain application data.
• Handle business logic and state.
• Communicate with data sources like databases or APIs.
In Android, this could be classes like User, Product, or a data repository that
manages data.
2. View
The View is responsible for displaying the UI and presenting data to the
user. It observes changes in the Model and updates the UI accordingly. It
doesn't contain any business logic but focuses on the presentation layer.
In Android, Views are typically activities, fragments, and UI elements
like buttons, text fields, and lists.
• Responsibilities:
• Render UI components.
• Display data from the Model.
• Pass user interactions (e.g., button
clicks) to the Controller.
In Android, this could be Activity or Fragment classes with
XML layout files defining the UI elements. Controller
The Controller acts as an intermediary between the
Model and the View. It listens for user inputs from the
View, updates the Model based on those inputs, and
informs the View to update the UI. The Controller is
responsible for handling logic based on user
interaction, such as clicking a button or submitting a
form.
• Responsibilities:
• Handle user events (like clicks).
• Update the Model based on user actions.
• Refresh the View based on changes in
the Model.
In Android, the Controller is typically an Activity or
Fragment, which listens to user actions (like button
presses) and updates the Model and View accordingly.
Flow of MVC in Android:
1. The View triggers user events (e.g., button click).
2. The Controller reacts by processing the event and updating the Model.
3. The Model changes its state, and the Controller instructs the View to update the UI with
the new data.
4. The View reflects the updated data from the Model.
Advantages of MVC in Android
• Separation of Concerns: Each component has its own responsibility, making the
codebase easier to manage.
• Reusability: Models can be reused across different Views.
• Testability: Each component can be tested independently, improving overall code quality.
• Maintainability: Changes in one component (like the View) do not directly affect the
others, making it easier to update the application.
Example
Model (The Books and Database): The Model in our library is like the actual books on the shelves
and the library's database system. It contains all the information about each book: its title, author,
ISBN, location in the library, whether it's checked out or not, etc.
1. View (The Library Building and Interfaces): The View is like the physical layout of the
library and all the ways patrons interact with it:
3. Controller (The Librarians): The librarians act as the Controller. They manage interactions
between the patrons (users) and the library system (Model). They:
1. Model:
o In the library: Books and the database
o In Android: Data classes, database interactions, network calls
2. View:
o In the library: Computer terminals, bookshelves, checkout counter
o In Android: XML layouts, Activities, Fragments, RecyclerViews
3. Controller:
o In the library: Librarians
o In Android: Activity/Fragment logic
Explanation:
• Each piece of furniture (sofa,
TV stand, dining table)
represents a Fragment.
• The room layout represents
the Activity that hosts these Fragments.
• Just like you can rearrange furniture for different room sizes or purposes, you can
rearrange Fragments for different screen sizes or orientations in Android.
Examples:
1. In a small apartment (smartphone), you might have these furniture pieces (Fragments) in
separate rooms (Activities).
2. In a large house (tablet), you could have multiple pieces in the same room (multiple
Fragments in one Activity).
Key benefits:
• Reusability: Use the same "furniture" (Fragment) in different rooms (Activities).
• Flexibility: Easily rearrange your layout for different screen sizes or orientations.
• Modularity: Update or replace one piece of furniture without affecting the others.
Types of Android Fragments
1. Single Fragment: Display only one single view on the device screen. This type of
fragment in android is mostly used for mobile phones.
2. List Fragment: This Fragment is used to display a list-view from which the user can
select the desired sub-activity. The menu drawer of apps like Gmail is the best example
of this kind of android fragment.
3. Fragment Transaction: This kind of fragments in android supports the transition from
one fragment in android to another at run time. Users can switch between multiple
fragments like switching tabs.
Android Fragment Lifecycle
onAttach() The very first method to be called when the fragment has been
associated with the activity. This method executes only once during
the lifetime of a fragment.
When we attach fragment(child) to Main(parent) activity then it call
first and then not call this method any time(like you run an app and
close and reopen) simple means that this method call only one time.
onCreate() This method initializes the fragment by adding all the required
attributes and components.
onCreateView() System calls this method to create the user interface of the fragment.
The root of the fragment’s layout is returned as the View component
by this method to draw the UI.
You should inflate your layout in onCreateView but shouldn’t
initialize other views using findViewById in onCreateView.
onViewCreated() It indicates that the activity has been created in which the fragment
exists. View hierarchy of the fragment also instantiated before this
function call.
onStart() The system invokes this method to make the fragment visible on the
user’s device.
onPause() It indicates that the user is leaving the fragment. System call this
method to commit the changes made to the fragment.
onDestroy() It is called to perform the final clean up of fragment’s state and its
lifecycle.
onDetach() The system executes this method to disassociate the fragment from its
host activity.
It will call when your fragment Destroy(app crash or attach new
fragment with existing fragment)
Explanation:
• The chef (your Android app)
has a core set of cooking
skills (core functionality).
• The chef adapts these skills
to different environments:
1. Restaurant kitchen
(smartphone):
Efficient, streamlined
cooking for
individual orders.
2. Catering kitchen (tablet): Preparing larger quantities, more complex presentations.
3. Food truck (wearable): Quick, simplified menu for on-the-go customers.
4. Home kitchen (TV): Leisurely cooking with a focus on visual presentation.
How this relates to Android development:
1. Core Functionality: Your app's main features (like the chef's cooking skills) remain
consistent across platforms.
2. UI Adaptation:
o For smartphones: Compact, touch-optimized interfaces.
o For tablets: Expanded layouts, multi-pane designs.
o For wearables: Simplified UI, focus on quick interactions.
o For TVs: Remote-control friendly interface, emphasis on visual content.
3. Feature Customization:
o Enable/disable features based on device capabilities (like a chef adjusting the menu
based on kitchen equipment).
o Optimize performance for each platform (like a chef adjusting cooking techniques
for different stoves).
Key considerations:
• Responsive Design: Use layouts that adapt to different screen sizes (like a chef arranging
dishes differently for various table sizes).
• Input Methods: Account for touch, keyboard, remote control, or voice input (like a chef
handling different order-taking methods).
• Performance Optimization: Ensure your app runs smoothly on less powerful devices (like
a chef creating efficient recipes for limited kitchen setups).
Multi-platform development for Android is achieved by creating applications that can run on
multiple operating systems (such as iOS, Windows, and web platforms) using a single codebase.
This approach minimizes development time, reduces costs, and provides a unified user experience
across devices. Several popular frameworks and tools enable multi-platform development for
Android, with Flutter, React Native, and Kotlin Multiplatform among the most common.
1. Flutter
Flutter is an open-source UI toolkit developed by Google that allows developers to create
natively compiled applications for mobile, web, and desktop from a single codebase. It uses the
Dart language, which compiles to native code, resulting in high-performance applications.
Key Features of Flutter:
• Single Codebase: Develops for Android, iOS, web, and desktop simultaneously.
• Hot Reload: Allows developers to see changes instantly, speeding up the development
process.
• Widgets: Flutter provides a rich set of customizable widgets that enable seamless app
designs across platforms.
2. React Native
React Native is a JavaScript framework powered by Facebook that uses React to build
applications for Android, iOS, and web. Unlike Flutter, React Native bridges JavaScript and
native components, allowing developers to use JavaScript for the UI and native code for device-
specific features.
Key Features of React Native:
• Reusable Code: Code can be reused across multiple platforms, reducing development
time.
• Community and Libraries: React Native has a large ecosystem, providing various
libraries for accessing device-specific features.
• Fast Refresh: Allows developers to see UI changes instantly, improving development
efficiency.
3. Kotlin Multiplatform Mobile (KMM)
Kotlin Multiplatform Mobile (KMM) is a newer technology by JetBrains that allows for code
sharing across Android and iOS. Unlike Flutter and React Native, KMM focuses on sharing
business logic (not UI), enabling developers to use native UI components on each platform while
sharing code for data processing, networking, and other business operations.
Key Features of KMM:
• Native UI: Each platform can maintain its own UI, leading to a more native look and feel.
• Shared Business Logic: Common code for business logic, reducing duplicate work.
• Full Kotlin Support: Great for Android developers who are familiar with Kotlin.
• Flutter is ideal for creating identical UIs on all platforms, as it provides rich UI components
and runs on various platforms.
• React Native allows JavaScript-based UI development with native-like performance,
leveraging a vast ecosystem.
• Kotlin Multiplatform Mobile (KMM) enables native UI on Android and iOS while sharing
business logic, making it perfect for developers focusing on native appearance.
In Android development, layouts define how user interface elements are arranged on the screen.
Different layout types help developers design interfaces that adapt to various device sizes and
orientations. Here are the main layout types used in Android applications:
1. Linear Layout
• Definition: Linear Layout arranges UI elements in a single row (horizontal) or column
(vertical).
• Explanation: Elements are placed one after another, either horizontally or vertically.
Linear Layout is simple but can be limited when you need a complex UI structure.
• Use Case: Ideal for lists, menus, or stacking elements in a single direction.
2. Relative Layout
• Definition: Relative Layout positions elements relative to each other or the parent
container.
• Explanation: You can align elements with respect to the edges of the layout or to other
elements within the layout. This provides more flexibility for complex interfaces, but it
can become difficult to manage if the layout has many elements.
• Use Case: Useful for placing elements with more control over their positions, especially
when you need elements aligned relative to each other.
3. Constraint Layout
• Definition: Constraint Layout enables you to create complex layouts by defining
constraints on each element.
• Explanation: Each element can be constrained to another element or the layout itself.
This allows for positioning elements in ways similar to Relative Layout but with much
more flexibility and efficiency, reducing the need for nested layouts.
• Use Case: Recommended for complex layouts that need to be responsive across different
screen sizes, often used in modern Android applications.
4. Frame Layout
• Definition: Frame Layout is designed to hold a single view or multiple views that overlap
each other.
• Explanation: Elements are stacked one on top of another, with the first element at the
bottom. Frame Layout is best used for a single view or for creating overlapping views.
• Use Case: Useful when you want to show a single view at a time or create simple
overlays, such as an image with a text label on top.
5. Grid Layout
• Definition: Grid Layout arranges elements in a grid of rows and columns.
• Explanation: You can specify the number of rows and columns, and elements are placed
in the grid accordingly. This layout is useful for creating interfaces with evenly
distributed elements, like image galleries.
• Use Case: Ideal for creating grids of items, such as image galleries, or organizing
multiple buttons in a grid format.
In Android, the Canvas class is used for drawing 2D graphics. You can draw shapes, lines, text,
and bitmaps directly on the screen or within a custom view by using the Canvas along with the
Paint class, which holds style and color information for the drawings.
Steps for Canvas Drawing in Android
1. Create a Custom View: First, create a custom view by subclassing the View class.
2. Override onDraw Method: Override the onDraw method in the custom view. This is
where you will use the Canvas object to draw your shapes or other graphics.
3. Use Canvas and Paint: Use the Canvas and Paint classes to define colors, styles, and
shapes.
Key Classes and Methods for Canvas Drawing
1. Canvas Class
o Purpose: The Canvas class provides methods to draw primitives (basic shapes),
text, and bitmaps.
o Commonly Used Methods:
▪ drawLine(float startX, float startY, float stopX, float stopY, Paint paint):
Draws a line between two points.
▪ drawRect(float left, float top, float right, float bottom, Paint paint): Draws
a rectangle.
▪ drawCircle(float cx, float cy, float radius, Paint paint): Draws a circle.
▪ drawOval(float left, float top, float right, float bottom, Paint paint): Draws
an oval.
▪ drawText(String text, float x, float y, Paint paint): Draws text.
▪ drawArc(RectF oval, float startAngle, float sweepAngle, boolean
useCenter, Paint paint): Draws an arc.
▪ drawBitmap(Bitmap bitmap, float left, float top, Paint paint): Draws a
bitmap image.
2. Paint Class
o Purpose: The Paint class holds style and color information about how to draw
geometries, text, and bitmaps.
o Common Properties:
▪ setColor(int color): Sets the color of the paint.
▪ setStyle(Paint.Style style): Sets the style (e.g., FILL, STROKE,
FILL_AND_STROKE).
▪ setStrokeWidth(float width): Sets the width of the stroke.
▪ setTextSize(float textSize): Sets the text size.
Example
public class CustomView extends View {
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw a line
canvas.drawLine(50, 50, 200, 200, paint);
// Draw a rectangle
canvas.drawRect(100, 300, 400, 500, paint);
// Draw a circle
canvas.drawCircle(200, 700, 100, paint);
// Draw text
paint.setTextSize(50);
canvas.drawText("Hello Canvas", 100, 900, paint);
}
}
In Android mobile applications, a shadow widget refers to a UI component with shadow effects
added to enhance its visual depth and give the appearance of elevation. Shadow effects help
simulate 3D effects on flat screens, creating a sense of hierarchy and depth, making the app
interface more visually engaging and guiding users' attention to specific elements.
Implementation of Shadows
The Android framework provides built-in support for shadows, especially in Material Design
components, which use elevation and shadow to convey depth. Key attributes include:
1. Elevation Attribute: Setting the android:elevation property on a view (available from
API level 21) applies a shadow based on the view’s position. Higher values increase the
shadow’s offset and opacity, making elements appear raised.
2. Z-Index: The elevation property also affects a view’s z-index in relation to other views,
determining its visual priority. This means views with higher elevation appear “on top” of
others.
To set the elevation of a view in the code of an activity, use the View.setElevation() method.
Handling databases in Android applications allows for effective data storage, retrieval, and
management. Android provides a couple of primary methods for managing databases:
1. Using Android’s SQLite Database Class (SQLiteDatabase)
2. Using the Room Database API
Both approaches offer ways to perform CRUD (Create, Read, Update, Delete) operations in a
structured, persistent manner. Here’s a look at each method and an example of how they’re used.
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_USERS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_AGE + " INTEGER)";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
onCreate(db);
}
@ColumnInfo(name = "age")
public int age;
}
// DAO Interface
@Dao
public interface UserDao {
@Insert
void insert(User user);
// Database Class
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
Using the Database in an Activity:
AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "user_database").build();
// Insert user
User user = new User();
user.name = "John Doe";
user.age = 28;
userDao.insert(user);
// Retrieve users
List<User> userList = userDao.getAllUsers();
Explanation:
• The User class represents the table.
• The UserDao interface provides methods for interacting with the database without
needing raw SQL.
• AppDatabase manages the database instance, creating it if it doesn’t already exist.
Advantages:
• Room offers compile-time verification, reducing the risk of runtime SQL errors.
• Built-in support for LiveData and Observable, making it easier to work with data in real-
time.
• Room handles database migrations and has support for complex data structures.
Limitations:
• Room requires more setup than SQLite for simple applications.
• Room does not directly support certain advanced SQL operations (like triggers) without
extra configuration.
Summary
Using SQLiteDatabase directly offers more control over SQL but is prone to errors and requires
extensive code management. The Room API, on the other hand, simplifies database management
with a more structured, object-oriented approach, helping prevent runtime errors and making it
easier to handle complex data interactions. Room is now the preferred choice in Android
development due to its modern, scalable architecture.