MAD Chapter 3
MAD Chapter 3
UNIT - 1
Chapter 3 : Using Activities, Fragments and Intents in Android
Activity Lifecycle
In Android development, an Activity represents a single screen with a user interface, functioning
as a crucial component of an application. Understanding the Activity Lifecycle is essential for
managing how activities are created, paused, resumed, and destroyed, ensuring optimal
performance and a seamless user experience.
The Activity Lifecycle comprises several states, each corresponding to a specific callback
method:
1. onCreate(): Invoked when the activity is first created. This is where you initialize
essential components, set up the user interface, and perform one-time setup procedures.
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.Layout.activity_main);
}
2. onStart(): Called when the activity becomes visible to the user but is not yet interactive.
At this point, the activity is in the foreground.
@Override
protected void onStart()
{
super.onStart();
}
3. onResume(): Executed when the activity starts interacting with the user. The activity is
now at the top of the activity stack and receives user input.
@Override
protected void onResume()
{
super.onResume();
}
4. onPause(): Triggered when the system is about to resume another activity, indicating that
the current activity is no longer in the foreground. This is where you should save any
unsaved data and release resources that are not needed while the activity is paused.
@Override
protected void onPause()
{
super.onPause();
}
5. onStop(): Occurs when the activity is no longer visible to the user. This can happen when
a new activity starts, or the current activity is being destroyed. At this stage, the activity
should release resources that are not needed while the activity is not visible.
@Override
protected void onStop()
{
super. onStop();
}
6. onDestroy(): Called before the activity is destroyed. This is the final call that the activity
receives and is used to clean up resources that have not yet been released.
@Override
protected void onDestroy()
{
super. onDestroy();
}
7. onRestart(): Invoked after the activity has been stopped and just before it is started
again. This is typically used to reinitialize components that were released during
onStop().
@Override
protected void onRestart()
{
super. onRestart();
}
Visual Representation
User Interface Management: An activity is responsible for rendering the user interface,
allowing users to interact with the application. Developers define the layout and behavior of UI
components within an activity.
Event Handling: Activities process user inputs like clicks, touches, and gestures, enabling the
application to respond to user actions appropriately.
Intent Management: Activities can initiate other activities or applications using intents,
facilitating inter-component communication and task delegation. For example, an activity can
send an intent to open a web page in a browser.
Data Persistence: Activities can save and restore UI state and user data during lifecycle
events, such as configuration changes or when the system reclaims resources, ensuring continuity
in user experience.
Fragment Management: Activities can host multiple fragments, which are modular
components representing portions of the user interface, allowing for more flexible and dynamic
UI designs.
Permissions Handling: Activities can request runtime permissions from users to access
protected resources like the camera or location services, ensuring compliance with security
protocols.
In Android development, styles and themes are essential tools that allow developers to define
the visual aesthetics and consistent design elements of an application. They enable the separation
of design details from the core UI structure and behavior, akin to stylesheets in web design.
Styles:
A style is a collection of attributes that specify the appearance and format for a UI element, such
as a View or window. By defining styles, developers can ensure a consistent look and feel across
various UI components. Styles are typically defined in XML resource files, separate from the
layout XML, promoting modularity and reusability.
<TextView
style="@style/CustomTextStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!" />
Themes:
A theme is a broader set of styles or attributes that apply to an entire application, activity, or
view hierarchy. Themes define the overall look and feel of an app, including colors, typography,
and shapes, ensuring a cohesive user experience.
<resources>
Applying this theme in the AndroidManifest.xml ensures that the specified styles are consistently
used throughout the application:
<application
android:theme="@style/AppTheme">
<!-- Activities and other components -->
</application>
Best Practices:
Consistency: Utilize styles and themes to maintain a uniform design across the
application, enhancing user experience.
Modularity: Define styles and themes in separate XML files to promote clean code
architecture and ease of maintenance.
Customization: Leverage themes to allow users to switch between different visual
modes, such as light and dark themes, accommodating user preferences.
Dialogs in activity
In Android development, a dialog is a small window that prompts the user to make a decision or enter
additional information. Unlike activities, dialogs do not occupy the entire screen and are typically used
for modal events that require users to take an action before proceeding.
Below is a Java example demonstrating how to create and display an AlertDialog within an
activity:
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
Explanation:
Alert Dialog: This dialog displays a title, a message, and up to three buttons. It's commonly
used to present users with information or to prompt them for a decision.
DatePicker Dialog: This dialog provides a user interface for selecting a date. It's useful in
scenarios where the user needs to input a specific date, such as setting a reminder or scheduling
an event.
TimePicker Dialog: Similar to the DatePicker Dialog, this dialog allows users to select a
time. It's often used in applications that require time input, like setting alarms or meeting times.
Custom Dialog: Developers can create custom dialogs tailored to specific application needs
by defining a custom layout. This allows for flexibility in designing the dialog's appearance and
behavior.
ButtomSheet Dialog: This dialog slides up from the bottom of the screen. This provides a
modern way to present actions to users.
ProgressBar in Android
In Android development, a ProgressBar is a user interface element that visually represents the
progress of an ongoing operation, such as downloading a file or loading content. It provides
users with feedback on the status of tasks, enhancing the overall user experience.
1. Determinate ProgressBar: Displays a specific quantity of progress. Use this when the
duration of the task is known, allowing the progress to be measured and displayed
accurately. Typically represented as a horizontal bar that fills up as the task progresses.
2. Indeterminate ProgressBar: Indicates that an operation is occurring without specifying
the amount of progress. Use this when the duration of the task is unknown or cannot be
determined. Often displayed as a cyclic animation, such as a spinning wheel.
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="50" />
<ProgressBar
android:id="@+id/progressBarIndeterminate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true" />
Intent
In Android development, an Intent is a messaging object used to request an action from another
app component, facilitating communication between different components, such as activities,
services, and broadcast receivers.
To navigate from one activity to another, you can use an explicit intent that specifies the target
activity. Here's how to implement this:
1. Create the Activities:
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
MainActivity.java activity_main.xml
package com.example.intentexample; <?xml version="1.0" encoding="utf-8"?>
import android.content.Intent; <LinearLayout
import android.os.Bundle; xmlns:android="http://schemas.android.com/ap
import android.view.View; k/res/android"
import android.widget.Button; android:layout_width="match_parent"
import androidx.appcompat.app.AppCompatActivity; android:layout_height="match_parent"
android:orientation="vertical"
public class MainActivity extends AppCompatActivity { android:gravity="center">
@Override
protected void onCreate(Bundle savedInstanceState) { <Button
super.onCreate(savedInstanceState); android:id="@+id/button"
setContentView(R.layout.activity_main); android:layout_width="wrap_content"
android:layout_height="wrap_content"
Button button = findViewById(R.id.button); android:text="Go to Second Activity"/>
button.setOnClickListener(new View.OnClickListener() { </LinearLayout>
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
SecondActivity.class);
MainActivity has a button. When clicked, it starts SecondActivity using an Intent and
passes a message.
SecondActivity retrieves the message using getIntent().getStringExtra("message")
and displays it in a TextView.
3. Data Transfer: Intents can carry data between components using key-value pairs, known
as "extras." This feature is particularly useful for passing information to the component
being started.
4. Intent Filters: Components can declare intent to specify the types of Intents
5. Broadcasting Messages: Intents can be used to broadcast messages to multiple
components simultaneously. For example, a system event like a low battery warning can
be broadcasted to notify all interested components.
6. Explicit and Implicit Intents: Developers can use explicit intents to target a specific
component within the app or implicit intents trigger action without specifying the target.
Types of Intents
In Android development, Intents are used for communication between components (activities,
services, etc.). There are two main types of intents:
1. Explicit Intent
2. Implicit Intent
{
startActivity(intent);
}
1. Important Methods in Intent Class
Method Description
getIntExtra(String name, int defaultValue) Retrieves an integer extra from the intent.
Method Description
2. Components in Detail
A) <action> (Required)
B) <category> (Optional)
android.intent.category.LAUNCHER Specifies the app's main entry point (home screen icon).
C) <data> (Optional)
Attribute Description
android:scheme Defines the URI scheme (e.g., http, https, mailto, tel).
Fragment
In Android development, a Fragment represents a reusable portion of your app's user interface.
Fragments allow for modular activity design, enabling you to divide the UI into discrete
components that can be combined in various configurations. Each fragment has its own lifecycle,
manages its own layout, and can handle its own input events. However, fragments cannot exist
independently; they must be hosted within an activity or another fragment.
Creating a Fragment:
Modularity and Reusability: Fragments introduce modularity and reusability into your
activity’s UI by allowing you to divide the UI into discrete chunks. Activities are ideal
for placing global elements around your app's user interface, such as a navigation drawer,
while fragments are better suited to define and manage the UI of a single screen or
portion of a screen.
Lifecycle Management: A fragment has its own lifecycle, This includes onCreate(),
onCreateView(), onStart(), onResume(), onPause(), onStop(), onDestroy() and
onDestroyView().
Flexible UI Design: Fragments enable flexible UI designs that can adapt to various
screen sizes and orientations. For example, on larger screens like tablets, multiple
fragments can be displayed side by side, while on smaller screens like phones, fragments
can be swapped in and out to optimize the user experience.
Communication : It can communicate with their host activity and other fragments.
Back Stack Management : With the introduction of the Navigation component, Android
supports multiple back stacks, especially useful for apps with complex navigation
patterns like bottom navigation or navigation drawers. This feature allows users to switch
between different sections of the app without losing their navigation state in each section.
Nested Fragment : Nested Fragments refer to fragments that are embedded within other
fragments. This hierarchical arrangement allows for more modular and flexible UI
designs, especially when dealing with complex layouts or dynamic content.
1. onAttach(Context context): Called when the fragment is first attached to its context
(activity). This is where you can access the activity instance the fragment is attached to.
@Override
public void onAttach(Context context) {
super.onAttach(context);
// Initialization code here
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize components
}
@Override
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Setup views here
}
java
CopyEdit
@Override
public void onStart() {
super.onStart();
// Fragment is visible
}
@Override
public void onResume() {
super.onResume();
// Fragment is active
}
7. onPause(): Called when the fragment is no longer in the foreground but still visible.
@Override
public void onPause() {
super.onPause();
// Fragment is pausing
}
@Override
public void onStop() {
super.onStop();
// Fragment is stopped
}
9. onDestroyView(): Called when the view hierarchy associated with the fragment is being
removed.
@Override
public void onDestroyView() {
super.onDestroyView();
// Clean up resources related to the view
}
@Override
public void onDestroy() {
super.onDestroy();
// Cleanup fragment resources
}
11. onDetach(): Called immediately prior to the fragment no longer being associated with its
activity.
@Override
public void onDetach() {
super.onDetach();
// Fragment is detached from activity
}