0% found this document useful (0 votes)
26 views13 pages

Unit 3 MAD

The document provides an overview of key components in Android development, including Activities, Intents, Fragments, and Layout Managers. It explains the lifecycle of Activities and Fragments, the types of Intents (explicit and implicit), and the various layout managers (Relative, Linear, Table, and Grid) used for UI design. Each section emphasizes the importance of understanding these concepts for creating effective and responsive Android applications.

Uploaded by

ashish.shonak037
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views13 pages

Unit 3 MAD

The document provides an overview of key components in Android development, including Activities, Intents, Fragments, and Layout Managers. It explains the lifecycle of Activities and Fragments, the types of Intents (explicit and implicit), and the various layout managers (Relative, Linear, Table, and Grid) used for UI design. Each section emphasizes the importance of understanding these concepts for creating effective and responsive Android applications.

Uploaded by

ashish.shonak037
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Activity, Activity Lifecycle, and Activity Example

Activity

An Activity in Android is a core component that provides a single screen with which
users can interact to perform a specific task, such as viewing a list, entering data, or
displaying information. Each activity acts as a window for the app's user interface and
is implemented as a subclass of the Activity class.

 Role in App:

 Each screen in an app is typically represented by an activity (e.g., login,


home, settings).

 Activities are loosely coupled; one activity can start another, even from a
different app, using intents.

 Activities must be declared in the app’s manifest file.

Activity Lifecycle

The Activity Lifecycle defines the sequence of states an activity goes through from
creation to destruction. Understanding and managing these states ensures your app
behaves correctly as users navigate, receive calls, or switch tasks.

Core Lifecycle Methods

Lifecycle Flow:

 When an activity is launched: onCreate() → onStart() → onResume()

 When another activity comes in front: onPause() → onStop()

 When returning to the activity: onRestart() → onStart() → onResume()

 When the activity is closed: onPause() → onStop() → onDestroy()


Importance:
Properly handling these callbacks helps manage resources, save user data, and
ensure a smooth user experience.

Activity Example

Below is a simple example demonstrating an activity in Android:

1. Java File (MainActivity.java):


Intent, Implicit Intent, Explicit Intent in Android
Intent

An Intent in Android is a messaging object used to request an action from another


app component. Intents facilitate communication between different components (such
as activities, services, and broadcast receivers) within an app and between different
apps. They are commonly used to:

 Start a new activity (screen)

 Start a service

 Deliver a broadcast message

 Pass data between components

Types of Intents

There are two main types of intents in Android:

1. Explicit Intent

 Definition:
An explicit intent specifies the exact app component (such as an activity or
service) to handle the intent by providing the component’s class name.

 Usage:
Typically used to start a component within the same application, for example,
navigating from one activity to another.

 Example:

Here, SecondActivity is explicitly named, so the system knows exactly which


component to start.

 Manifest Requirement:
The target activity or service must be declared in the
app’s AndroidManifest.xml file.

2. Implicit Intent

 Definition:
An implicit intent does not specify a specific component. Instead, it declares a
general action to perform (such as viewing a web page, sending an email, or
displaying a location), allowing any app on the device that can handle the action
to respond.
 Usage:
Used when you want another app (or another component in any app) to handle
the action.

 Example:

Here, the system searches for any app that can handle the "view" action for the given
URL, such as a web browser.

 How It Works:
The Android system matches the intent with intent filters declared in the
manifest files of installed apps. If multiple apps can handle the intent, the user
is prompted to choose.

 Common Uses:

 Open a web page

 Dial a phone number

 View a map location

 Share content with other apps

Summary Table

Fragment, Fragment Lifecycle, Fragment Example,


Dynamic Fragment
Fragment

A Fragment in Android is a modular section of an activity, representing a portion of


the user interface or behavior within a larger activity. Fragments enable more flexible
and modular UI designs, especially for devices with varying screen sizes such as
tablets and phones. Unlike activities, fragments cannot exist independently; they
must be hosted within an activity. Each fragment has its own layout, lifecycle, and can
be reused across multiple activities. Fragments can be added, removed, or replaced
dynamically while the activity is running, allowing for responsive and adaptive UI
designs.

Key features of fragments:

 They encapsulate UI components and logic, making code more modular.

 Multiple fragments can be combined in a single activity to build multi-pane UIs.

 Fragments can be reused in different activities.

 They can be added or removed dynamically at runtime.

Fragment Lifecycle

The fragment lifecycle is closely tied to the lifecycle of its host activity but includes its
own distinct stages and callback methods. Understanding the fragment lifecycle is
crucial for managing resources, handling user interactions, and ensuring smooth
transitions.

Core Fragment Lifecycle Methods:

1. onAttach(): Called when the fragment is attached to its host activity.

2. onCreate(): Initializes the fragment; perform non-UI setup here.

3. onCreateView(): Inflates the fragment’s UI layout and returns the root view.

4. onViewCreated(): Called after the view is created; useful for initializing UI


components.

5. onActivityCreated(): Indicates the host activity’s onCreate() is complete; safe


to access activity data.

6. onStart(): Fragment becomes visible to the user.

7. onResume(): Fragment is active and interactive.

8. onPause(): Fragment is partially obscured; commit unsaved changes.

9. onStop(): Fragment is no longer visible.

10. onDestroyView(): Clean up resources related to the view.

11. onDestroy(): Final cleanup of fragment state.

12. onDetach(): Fragment is detached from the host activity.

Fragments also expose a Lifecycle object, allowing integration with lifecycle-aware


components for better resource management

Fragment Example

1. Creating a Fragment:
2. Adding the Fragment to an Activity (Static):

In the activity’s layout XML:


This approach allows you to add, replace, or remove fragments during runtime.

Dynamic Fragment

A Dynamic Fragment refers to fragments that are added, replaced, or removed from
an activity programmatically at runtime, rather than being statically declared in the
XML layout. This is typically managed using
the FragmentManager and FragmentTransaction classes.

Use cases for dynamic fragments:

 Adapting the UI to device orientation (e.g., showing two fragments side-by-side


in landscape and one at a time in portrait).

 Responding to user actions, such as displaying details when an item is selected


from a list.

Example of adding a dynamic fragment:

Dynamic fragments are essential for building adaptive and responsive interfaces,
especially for supporting different screen sizes and orientations.

Conclusion

Fragments provide a powerful way to create modular, reusable, and dynamic user
interfaces in Android. The fragment lifecycle, while similar to the activity lifecycle,
includes additional stages for managing the fragment’s UI and interaction with its host
activity. Static fragments are defined in XML, while dynamic fragments are managed
programmatically, enabling flexible and adaptive layouts that enhance the user
experience across a wide range of devices.

Android Menu: Options Menu, Context Menu, Popup


Menu
Android provides several types of menus to offer actions and options to users in a
structured and interactive way. The three fundamental types are the Options
Menu, Context Menu, and Popup Menu. Each serves a specific purpose and is
implemented differently within an app.

1. Options Menu

Purpose:
The Options Menu is used to present primary actions and settings related to the
current activity or app. It typically appears at the top of the screen when the user taps
the menu button or the overflow icon (three dots).

Features:

 Commonly used for global actions like "Settings," "Search," or "Help."

 Appears in the app bar or toolbar.

Implementation:

 Override the onCreateOptionsMenu(Menu menu) method in your activity.

 Inflate a menu XML file using MenuInflater.

Example:
The menu XML defines the menu items and their properties. When a user selects an
item, onOptionsItemSelected() handles the action.

2. Context Menu

Purpose:
A Context Menu provides context-specific actions for a particular view or item, usually
appearing when the user performs a long-press (long click) on that element.

Features:

 Used for actions like "Edit," "Delete," or "Share" relevant to the selected item.

 Only affects the selected content.

Implementation:

 Register the view for a context menu using registerForContextMenu(View view).

 Override onCreateContextMenu() to define menu items.

 Handle selections in onContextItemSelected().

Example:
3. Popup Menu

Purpose:
A Popup Menu is a floating menu anchored to a specific view, displaying a list of
actions in response to a user interaction (such as clicking a button).

Features:
 Appears as a small popup window near the triggering view.
 Used for showing a short list of options, such as sorting or filtering.
Implementation:
 Create a PopupMenu object and associate it with a view.
 Inflate the menu resource.
 Set a listener for menu item clicks.
Example:
Layout Manager: Relative Layout, Linear Layout, Table
Layout, Grid Layout
In Android development, layout managers (or layouts) are essential for organizing and
displaying user interface (UI) elements on the screen. Each layout manager provides a
unique way to arrange views, impacting both the visual structure and the usability of
an application. The most prominent layout managers are Relative Layout, Linear
Layout, Table Layout, and Grid Layout. Understanding their characteristics,
advantages, and appropriate use cases is crucial for designing effective Android UIs.

Relative Layout

Relative Layout is a powerful and flexible layout manager that allows developers to
position UI elements relative to one another or to the parent container. This means
that a view can be placed to the left, right, above, or below another view, or aligned
with the parent’s edges or center. Relative Layout is particularly useful for creating
complex interfaces without deeply nested hierarchies.

Advantages:

 Reduces the need for multiple nested layouts, which can improve performance.

 Enables dynamic and responsive UI designs, as elements can adjust their


positions based on others.

 Useful for forms, login screens, and toolbars where component relationships are
important.

Limitations:

 Can become difficult to manage if too many relationships are defined.

 Overuse may lead to maintenance challenges as the UI complexity grows.

Linear Layout

Linear Layout arranges its child views in a single direction-either vertically or


horizontally. All elements are placed one after another in the specified orientation.
Linear Layout is simple and intuitive, making it ideal for straightforward arrangements
such as lists, menus, or toolbars.

Advantages:
 Easy to implement and understand, especially for beginners.

 Supports weight distribution, allowing for proportional allocation of space among


child views.

 Ideal for sequential or stacked UI elements, such as forms or vertical menus.

Limitations:

 Deeply nested Linear Layouts can lead to performance issues.

 Not suitable for complex or highly interdependent UI arrangements.

Table Layout

Table Layout organizes its child views into rows and columns, similar to a table in
HTML or a spreadsheet. Each row is defined as a separate entity, and columns are
determined by the maximum number of cells in any row. Table Layout is best suited
for displaying data in a grid-like format.

Advantages:

 Excellent for presenting tabular data, such as schedules, calculators, or


comparison tables.

 Ensures alignment of data in rows and columns, making the UI orderly and
readable.

 Each row can have a different number of cells, offering some flexibility.

Limitations:

 Less flexible than Relative or Linear Layout for non-tabular designs.

 Managing complex tables with merged cells or varying row heights can be
challenging.

Grid Layout

Grid Layout is a more advanced layout manager that places child views in a
rectangular grid. Unlike Table Layout, Grid Layout allows for both row and column
spanning, giving developers more control over the positioning and sizing of UI
elements. Each child can occupy one or more cells, making it highly versatile for
modern UI designs.

Advantages:

 Ideal for creating uniform grids, such as photo galleries, dashboards, or settings
screens.

 Supports cell spanning, enabling complex arrangements without deep nesting.

 Offers a balance between flexibility and simplicity, reducing the need for
multiple nested layouts.

Limitations:

 May be more complex to configure than Linear or Table Layout for simple UIs.
 Requires careful planning of row and column counts for optimal results.

Comparative Analysis

 Relative Layout is best for flexible, interdependent UI arrangements, reducing


view hierarchy depth and improving performance for complex screens.

 Linear Layout is optimal for simple, sequential arrangements, such as forms or


toolbars, where views are stacked in a single direction.

 Table Layout excels at presenting structured, tabular data, ensuring clear


alignment and readability.

 Grid Layout is the preferred choice for uniform grids and advanced layouts,
offering cell spanning and efficient use of screen space.

The choice of layout manager depends on the specific requirements of the UI. For
instance, a login screen might use Relative Layout for flexible positioning, a settings
menu could use Linear Layout for simplicity, a calculator might benefit from Table
Layout, and a photo gallery would be best served by Grid Layout.

Conclusion

Layout managers are foundational to Android UI design. Mastery of Relative Layout,


Linear Layout, Table Layout, and Grid Layout empowers developers to create efficient,
visually appealing, and responsive interfaces. Selecting the appropriate layout
manager not only enhances the user experience but also contributes to better app
performance and maintainability. Understanding the strengths and limitations of each
layout ensures that developers can tackle a wide range of design challenges in
Android application development.

You might also like