KEMBAR78
Mobile Dev Final Version | PDF | Mobile App | Android (Operating System)
0% found this document useful (0 votes)
34 views136 pages

Mobile Dev Final Version

Mobile development involves creating applications for mobile devices, categorized into native, hybrid, and web apps. The document outlines the distribution of mobile apps, the growing demand for mobile development, and the challenges faced, such as device compatibility and performance optimization. It also discusses various mobile frameworks, the Android operating system, and the structure of Android projects, including the use of Gradle and XML for app development.
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)
34 views136 pages

Mobile Dev Final Version

Mobile development involves creating applications for mobile devices, categorized into native, hybrid, and web apps. The document outlines the distribution of mobile apps, the growing demand for mobile development, and the challenges faced, such as device compatibility and performance optimization. It also discusses various mobile frameworks, the Android operating system, and the structure of Android projects, including the use of Gradle and XML for app development.
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/ 136

2024-2025

MOBILE DEVELOPMENT

Teacher : Mohamed Hedi


Mahfoudh mohamed.mahfoudh.7@gmail.com
WHAT IS MOBILE DEVELOPMENT?
❑ Mobile development means creating apps for mobile devices like smartphones and tablets.
These apps can be:
•Native Apps → Built for a specific system (like Android or iOS).
•Hybrid Apps → Work on multiple systems using web technologies.
•Web Apps → Apps that run in a web browser, like a website.

2
HOW ARE MOBILE APPS DISTRIBUTED?
Mobile apps are usually downloaded from official stores controlled by smartphone companies.
Types of App Stores:
Paid Apps → Users pay to download the app.
Free Apps → Users download for free, but apps may show ads.

Examples of app stores: Google Play Store (Android) and App Store (iOS).

Google Play App Store Microsoft Store ❑ Huawei Store


(Android OS), (Apple OS) (Windows (Harmony OS).
Mobile)
3
WHY MOBILE DEVELOPMENT?
❑ Accessibility & Mobility

•Smartphones are everywhere and always within reach.


•Users can access services and information in real-time, anytime, anywhere.
That's why mobile apps are so important today!

4
WHY MOBILE DEVELOPMENT?
❑ Growing Mobile Market

The demand for mobile apps is increasing rapidly.


Mobile has become an essential part of daily life.
This shows why mobile development is a great opportunity!

5
WHY MOBILE DEVELOPMENT?
❑ Better User Experience

Optimized for Mobile → Apps are designed for easy use on small screens.
Push Notifications → Keep users updated in real time.
Hardware Access → Use GPS, camera, and sensors for more features.
This makes mobile apps fast, interactive, and user-friendly!

6
CHALLENGES OF MOBILE DEVELOPMENT
1️⃣ Limited Size & Power
Smartphones are less powerful than PCs.
Less RAM & weaker processors require optimized code.
Poor optimization = slow apps!

2️⃣ Different Screen Sizes


Phones have small, big, and even foldable screens.
Apps must use responsive design to adapt.

3️⃣ Different Operating Systems


Android vs. iOS → Different programming languages & rules.
OS updates may break some features.

4️⃣ Battery Management


Heavy apps (games, videos) drain battery quickly.
Avoid unnecessary background processes to save power.

Good developers optimize apps to work smoothly on all devices!


7
TYPES OF MOBILE APPLICATIONS
Applications Natives Applications Web Applications Hybrides

▪ Built for one specific


▪ Run inside a browser ▪ A mix of native & web
system (Android or iOS).
(Chrome, Safari, etc.). apps.
Use system languages:
Made with HTML, CSS, Made with Ionic, React
Java/Kotlin (Android), Swift
JavaScript → No need to Native, Flutter → One code
(iOS).
install. for Android & iOS.
Best performance & full
Examples: Facebook Web, Examples: Instagram,
access to phone features (GPS,
Google Docs online. Twitter, Uber.
camera, sensors).
Pros: Easy updates, works on Pros: Single codebase for all
Examples: WhatsApp,
any device. platforms.
Instagram, Google Maps.
Cons: Slower & limited Cons: Not as fast as native
Pros: Fast & smooth
phone feature : cannot fully apps.
performance.
access device features like
Cons: Expensive → Need
Bluetooth, sensors.
separate versions for each OS.

8
TYPES OF MOBILE APPLICATIONS
Which Type to Choose?
Native → Best performance but expensive .
Web → Easy to develop but limited features .
Hybrid → Good balance between performance & cost .

The choice depends on the project and budget!

9
MAIN MOBILE FRAMEWORKS
What is a Mobile Framework?
A mobile framework is a tool that simplifies mobile app development by providing ready-to-use
components.
Speeds up development
Reduces the amount of code needed

Frameworks help developers build apps faster and more efficiently!

React Native (Facebook) Flutter (Google)

Developed by Facebook Developed by Google


Uses JavaScript & React to build hybrid Uses Dart and provides a fast & smooth UI.
apps (Android & iOS). Examples: Google Ads, BMW App, Alibaba.
Examples: Instagram, Facebook, Uber Eats. Advantage: Performance close to native
Advantage: One codebase for Android & apps .
iOS. Disadvantage: Requires learning Dart .
Disadvantage: Less performance
compared to native apps.

10
PRINCIPAUX FRAMEWORKS MOBILE

Conclusion: Which Framework to Choose?


React Native → Best for JavaScript developers .
Flutter → Near-native performance .
The choice depends on the project, skills, and requirements!

11
MOBILE OS
Why Learn Android?

1️⃣ Android dominates the market


2️⃣ More job opportunities
3️⃣ Flexible & Open Source
4️⃣ Compatible with more devices

Conclusion

Android is essential in the mobile world.


Easy to learn with Java/Kotlin.
Better job prospects & huge user base.
Learning Android is a great choice to
become a mobile developer!

12
ANDROID
What is Android?

Android is an open-source operating system for mobile devices (smartphones, tablets, etc.).
It is based on the Linux kernel and the Java programming platform.
Originally created by the startup Android Inc., it was later acquired by Google in 2005.

Advantages of Android :

Open-source → The code is free and modifiable. Developers can use libraries like OpenGL (for 2D/3D
graphics) and SQLite (for databases).
Affordable → Android is almost free. Publishing an app on the Play Store costs only $25. Developers
keep 70% of the revenue, while Google takes 30%.
Easy to develop → Android provides simple and powerful APIs, making development faster and
more efficient.

13
WHAT IS AN ANDROID API?
❑ An API (Application Programming Interface) is a set of functions and classes provided by
Android that allows developers to access system features.
❑ Each API version introduces new features, and its version number indicates the functionalities
available.
Backward Compatibility → Newer API versions are usually compatible with older ones.
Challenge → Many users have older smartphones that do not support the latest APIs.

Problem Example:
Imagine you want to develop an app that uses Facial Recognition to unlock access.
Android 10 (API 29) and above support this feature.
But older devices running Android 8 (API 26) do not support it.
Developers must carefully choose an API that balances:
Market compatibility → Works on most smartphones.
Desired features → Includes the latest functionalities.

Examples of Android APIs:

Camera API → Allows taking photos.


GPS (Location) API → Retrieves the phone's location.
14
Notification API → Sends notifications to users.
WHAT IS AN ANDROID API?

15
WHAT IS AN ANDROID SDK?
Le SDK (Software Development Kit) est un ensemble d'outils permettant de développer des applications
Android. Il contient :
Les API Android (pour interagir avec le système).
Des outils de développement (compilateur, débogueur, émulateur AVD(Android Virtual Device), etc.).
La documentation officielle pour guider les développeurs.

Différence entre API et SDK Android


Critère API Android SDK Android
Ensemble de fonctions pour Ensemble d'outils pour
Définition
interagir avec Android développer une application
Classes, méthodes (ex: API + Émulateur + Outils de
Contenu
Camera API, Location API) compilation
Permet d'utiliser des Permet de créer, tester et
Utilisation
fonctionnalités du téléphone compiler une app
LocationManager.getLastKno Android Studio + Debugger +
Exemple
wnLocation() API Android

Le SDK inclut les API, mais les API ne suffisent pas pour développer une app sans le SDK ! 16
ARCHITECTURE D’ANDROID

l’architecture du système Android


s’appuie essentiellement sur quatre
principaux :
o Le noyau Linux
o Les librairies ( bibliothèques) et
l’environnement d’exécution
o Le module de développement
d’applications
o Les différentes applications

17
MACHINE VIRTUELLE
❑ Les applications Android sont écrites en Java, mais elles ne sont pas exécutées par une machine
virtuelle Java JVM.

❑ Les applications Java standard ne fonctionnent pas nativement sous Android.

❑ Les applications Android sont exécutées par une machine virtuelle spécifique appelée Dalvik (
jusqu’`a la version 5.0 Lollipop, sortie en 2014) et actuellement ART , et non par une JVM classique.

18
MÉTHODES DE DÉVELOPPEMENT
❑ il y a deux manières pour développer une application Android :

o Méthode classique : en utilisant un IDE (Eclipse) + JDK + SDK


o Méthode moderne : en utilisant Android Studio

❑ Android Studio, le IDE Android, offre :


o Un éditeur de sources et de ressources.
o Des outils de compilation, notamment Gradle. Des outils de test et de mise au point.

https://developer.android.com/studio?hl=en 19
START A NEW ANDROID STUDIO PROJECT

20
START A NEW ANDROID STUDIO PROJECT

21
START A NEW ANDROID STUDIO PROJECT

• MinSDK (Minimum SDK) is the lowest Android version your app can run on.
• The percentage % shows how many active Android devices support your chosen
MinSDK.

22
START A NEW ANDROID STUDIO PROJECT
When you create a new Android project, you have to wait because Android Studio is setting up your project.

What happens during this time?

1.Gradle Sync – It downloads and configures the necessary dependencies.


2.Project Setup – It generates the required files and folders.
3.Indexing – Android Studio scans the project to enable features like autocomplete and error checking.
This process ensures that everything is ready before you start coding.
In the following sections of this course, we will detail each directory.

Notice : an internet connection is recommended but not always required.

When is the internet needed?


1.First-time setup – Android Studio may need to download Gradle files and dependencies.
2.New dependencies – If your project uses external libraries, they are downloaded from the internet.
3.SDK updates – If your chosen MinSDK or Target SDK is not installed, Android Studio will download it.

23
PROJECT STRUCTURE
The general structure of an Android project consists of two main directories:

•1️⃣ Gradle Scripts

•2️⃣ App

In the following sections of this course, we will detail each directory. But Before that we first need to
understand what is an Activity is in Android development.
24
WHAT IS AN ACTIVITY?
❑ Before we dive into the project folders and files, we first need to understand what an Activity is in
Android development.
❑ In Android development, an Activity represents a single screen of an application. Each app is made
up of multiple screens (activities).
❑ Each activity consists of:
A Java/Kotlin logic file (handles the functionality like button click)
An XML layout file (defines the UI design)

Example: Facebook App


When you open Facebook, it automatically displays the Home Screen.
The Home Screen has a logic file (Java/Kotlin) that controls its behavior.
It also has a UI layout file (XML) that defines elements (called Views) like buttons, checkboxes, radio
buttons, and text.
Facebook has multiple screens (activities) such as Marketplace, Videos, and Notifications, and
you can easily navigate between them.

25
PROJECT STRUCTURE(1️⃣GRADLE)
1️⃣ What is Gradle?

Gradle is a build automation tool used in


Android development. It helps manage
dependencies, compile code, and package
apps into APK files.
Why is Gradle important?
Manages dependencies – Downloads and
integrates external libraries.
Automates the build process – Converts
Java/Kotlin code into an APK.
Handles project configuration – Defines
SDK versions, permissions, and settings.
The build.gradle file manages
dependencies and configurations.

26
PROJECT STRUCTURE(2️⃣APP DIRECTORY)

2️⃣ App Directory

It contains the main files of an Android project:


•Manifests: Defines the application's components, permissions, and settings (such as the app's
launcher activity/screen). For example, if an application has three screens—one for Home, one
for Videos, and one for Account Management—the AndroidManifest.xml file allows us to specify
which screen (activity) should appear when the user opens the app.
•Java: Contains the app’s source code (Java/Kotlin) .It contains activities and other Java classes.
This is where you control the app's behavior and interact with the user.
27
•Res: Stores resources like images, layouts, and UI elements.
WHAT IS XML?
❑ Before understanding the AndroidManifest.xml file, we should first understand what the XML
language is.
❑ Definition:
•XML (Extensible Markup Language) is not a programming language like Java or C++ , is similar to
HTML in structure.
•It does not perform calculations but helps structure and format information. Instead, it is used to
structure, store, and format data in a readable and organized way.
❑ Question : Why is XML Important in Android?
•It is used to define UI layouts (buttons, text fields, etc.), resources, and data structures in Android
apps.
•It makes information easy to read, manage, and modify.
•Each UI element has attributes (e.g., android:text="Click Me" ).
Example in Android
•In Android, UI layouts (buttons, text fields, images) are designed using XML.

What happens here?


<Button
•XML defines the button’s size and text but does
android:layout_width="wrap_content"
not make it clickable or perform any action.
android:layout_height="wrap_content"
•The Java/Kotlin code handles the button’s logic
android:text="Click Me" /> 28
(e.g., what happens when clicked).
PROJECT STRUCTURE(MANIFESTS FILE)
<?xml version="1.0" encoding="utf-8"?>
The AndroidManifest.xml file declares the
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
elements of an application, with a ‘.’ before
xmlns:tools="http://schemas.android.com/tools">
the class name of the activities.
<application
android:allowBackup="true“ android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:exported="true“ Allows the activity
android:icon="@mipmap/ic_launcher"
to be accessed by other apps if needed
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
An intent-filter inside an <activity> tag tells
android:supportsRtl="true"
the system how this activity should behave
android:theme="@style/Theme.MyApplication"
and what types of intents it can handle.
tools:targetApi="31">
<activity
•This defines that this activity is the main entry point of
android:name=".MainActivity"
the application.
android:exported="true">
•It tells Android that this activity should be launched first
<intent-filter>
when the app starts.
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.
</intent-filter> •This marks the activity as one that should appear in the app
</activity> launcher (home screen). 29
</application> </manifest> •Without this, the app will not show an icon in the app drawer.
PROJECT STRUCTURE(JAVA FOLDER)
❑ Let's suppose that we have the code for this activity (MainActivity.java).

app/Java/com.example.isitcom extends AppCompatActivity : This means


MainActivity inherits from
public class MainActivity extends AppCompatActivity { AppCompatActivity, which is a base class for
@Override activities that use the modern Android
protected void onCreate(Bundle savedInstanceState) { components and compatibility features.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle savedInstanceState:
}
This parameter is used to save and
}
restore activity data (e.g., if the
device is rotated).
onCreate: Each activity has multiple lifecycle This parameter holds the previous
methods, which we will discuss later in this course. state of the activity (if it was paused
However, the most important one is the onCreate or restarted).
method. It is used to set up the user interface and It can be null if the activity is
initialize event listeners for user interactions. starting
30
PROJECT STRUCTURE(JAVA FOLDER)
Explanation:

• What happens inside onCreate()? This is where we set up the UI, initialize variables, and
define event listeners.
• super.onCreate(savedInstanceState): Calls the onCreate() method of the parent class
(AppCompatActivity).
• setContentView(R.layout.activity_main); : This loads and displays the UI of the activity.
• R.layout.activity_main :
• R: A generated class that links Java code with XML resources.
• layout.activity_main: Refers to the activity_main.xml file located in the
res/layout folder .This XML file defines the buttons, text fields, and UI
components for the activity.

31
ANDROID RESOURCES(THE RES FOLDER)
❑ Question : What Are Resources in Android?
Resources in Android are external files that store static content used by the app. These include images,
text, colors, and layouts.
❑ Question : Why Use Resources?
•Better Compatibility: Adapts apps to different screen sizes and devices.
•Easy Maintenance: Changes can be made without modifying the code.
•Multilingual Support: Helps in translating the app into different languages.

The res folder contains the


default locations for all
resources.

32
ANDROID RESOURCES
❑ Types of Resources:

1.Drawable: Images and graphics (PNG, JPEG, XML).


2.Layout: XML files defining the app’s UI.
3.Mipmap: Icons for different screen densities.
4.Values: Strings, colors, dimensions, and styles.
5.Raw: Music, videos, or HTML files.
6.Menu: XML files for creating app menus.

Example:
If an app displays a logo, instead of coding it, you store the image in the drawable folder
and reference it in the UI.

33
ACCESSING A RESOURCE
❑ Question : Resources are separate from Java code, but how can we access them in Java code?

❑ Answer: We use the R class, found in the R.java file.

❑ R class is:
1️⃣ Auto-generated by Android (inside R.java in the gen folder).
2️⃣ Read-only (we can’t manually edit it).
3️⃣ Static and final (IDs never change during runtime).
4️⃣ Used to reference all resources in the res folder.

34
ACCESSING A RESOURCE
Example 1: Accessing a Layout (activity_main.xml)
Suppose we have a layout file:
res/layout/activity_main.xml

The setContentView() method


is used to define which
XML layout file should be
displayed on the screen
when an activity starts.
This links the MainActivity.java
to the activity_main.xml layout file.

// java code
Java Code (MainActivity.java)
setContentView(R.layout.activity_main);
To use this layout in Java:
// java code 35
ACCESSING A RESOURCE
Example 2: Button Click Action in Android

Suppose we have the following button in our activity_main.xml layout file:


res/layout/activity_main.xml

<Button
android:id="@+id/myButton" We give the button an ID
android:layout_width="wrap_content" (@+id/myButton) so we can reference
android:layout_height="wrap_content" it in code.
android:text="Click Me" />

❑ In Android XML layouts, the @+id/myButton notation is used to define a unique identifier for a
UI element (View) so that it can be referenced in Java/Kotlin code. Let's break it down:

@ → Indicates that we are referring to an identifier.


+ → Tells Android to create a new ID if it does not already exist.
id → Specifies that the identifier belongs to the id category (used for UI elements).
myButton → The actual name of the identifier (you can choose any meaningful name)
36
ACCESSING A RESOURCE
Example 2: Button Click Action in Android
Suppose we have the following java code MainActivity.java file:
Java Code (MainActivity.java)

// Java code // findViewById(R.id.myButton) is used to reference


// Find the button by ID the button defined in the XML layout file.
Button myButton = findViewById(R.id.myButton);
// Set a click listener on the button setOnClickListener is used to handle the click
myButton.setOnClickListener(new View.OnClickListener() { event.
@Override The following line of code displays a Toast
public void onClick(View v) { message “Button Clicked!” when a button is clicked
// Display a toast message when the button is clicked
Toast.makeText(MainActivity.this, “Yeah!... I’m Toast ", Toast.LENGTH_SHORT).show(); }});

Declares a Button object named myButton. The Button class in Android


represents a clickable UI element.

37
WHAT IS A TOAST IN ANDROID?
❑ A Toast is a small pop-up message that briefly appears on the screen to provide feedback to the
user. It automatically disappears after a short duration and does not require user interaction.

•Context → The current screen (usually this or MainActivity.this).


•Duration → How long the Toast will be shown:
•Toast.LENGTH_SHORT → Short duration (about 2 seconds).
•Toast.LENGTH_LONG → Longer duration (about 3.5 seconds).
•show() → Displays the Toast message. 38
GRAPHICAL USER INTERFACE (GUI)
❑ In Android development, the User Interface (UI) is built using two main types of elements:

1️⃣ Layouts (View Groups) :


These are container elements that define how UI components(button , text , image , etc …)
are structured and positioned on the screen. They do not display content themselves but
organize Views within the interface.

2️⃣ Views :
These are the individual UI elements that users interact with, such as buttons, text fields, and
images.

39
LAYOUTS TYPES(LINEAR LAYOUT)
❑ Arranges child Views in a single direction: vertically or horizontally.
❑ Uses the attribute android:orientation to specify the direction.

<?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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>
40
This layout stacks the TextView and Button vertically.
LAYOUTS TYPES(RELATIVE LAYOUT )
❑ Positions Views relative to each other or the parent container.
❑ Uses attributes like android:layout_below, android:layout_alignParentRight, etc.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press Me"
android:layout_below="@id/title"/>
</RelativeLayout>
41
In this case, Button is positioned below TextView.
LAYOUTS TYPES(CONSTRAINTLAYOUT)
❑ ConstraintLayout allows for more flexible and complex layouts by defining constraints between UI
components. This is one of the most powerful layouts in Android.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android=http://schemas.android.com/apk/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"
android:orientation="horizontal">
<Button android:id="@+id/button1" android:layout_width="wrap_content"
android:layout_height="wrap_content“ android:text="Button 1"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"/>
<Button android:id="@+id/button2“ android:layout_width="wrap_content"
android:layout_height="wrap_content“ android:text="Button 2"
app:layout_constraintTop_toBottomOf="@id/button1"
app:layout_constraintLeft_toLeftOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
42
In this example, the buttons are constrained relative to each other and to the parent layout.
LAYOUTS TYPES(FRAMELAYOUT)
❑ FrameLayout is a simple layout that displays child views one on top of another. It is often used for
displaying a single child view or when you want views to overlap.

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


<FrameLayout
xmlns:android="http://schemas.android.com/apk/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"
android:orientation="horizontal">
<Button android:layout_width="wrap_content“
android:layout_height="wrap_content“ android:text="Button 1" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content“ android:text="Button 2"
android:layout_gravity="bottom|end"/>
</FrameLayout>

Here, both buttons will be stacked on top of each other, with the second button
43
positioned at the bottom-right corner.
LAYOUTS TYPES(TABLELAYOUT)
❑ TableLayout arranges child views in rows and columns, similar to a table. You can use it when you want
to organize items in a grid-like fashion.

44
This layout stacks the TextView and Button vertically.
LAYOUTS TYPES(GRIDLAYOUT)
❑ TableLayout arranges child views in rows and columns, similar to a table. You can use it when you want
to organize items in a grid-like fashion.

45
This layout stacks the TextView and Button vertically.
WHAT ARE VIEWS (WIDGET) ?
❑ A View is a UI element that the user interacts with. Here are common examples:
1.TextView – Displays text.

2.EditText – Input field for user text(Basic , Password , Phone Number ,…) .

3.Button – A clickable button.

4.ImageView – Displays images.

5.RadioButton: Allows selection of one option from a set of options.

6.CheckBox: A checkable box used for binary choices (checked/unchecked).

46
TEXTVIEW
❑ TextView is used to display text on the screen. You can customize its appearance, such as text size,
color, and alignment.

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="winter is coming"
android:textSize="18sp"
android:textColor="#FF5722"
/>

❑ We can also change the text dynamically in Java code:

TextView tvTitre = findViewById(R.id.tvTitre);


tvTitre.setText(“Say My Name");

47
TEXTVIEW
❑ Explanation:

android:text="winter is coming" : This is the text displayed in the TextView .

android:textSize="18sp“ : Specifies the text size in scale-independent pixels (sp).

android:textColor="#FF5722" : Specifies the text color using a hex value.

android:layout_width : This attribute defines the width of the view (the element in the layout). It can
take one of three values:
•wrap_content: The view will only be as wide as its content (i.e., it will "wrap" around the
content). For example, a TextView with the text "Hello" will only be as wide as the text "Hello".
•match_parent: The view will take up the full width of its parent container (usually the width of
the screen or parent layout).
•Specific dp value: You can define a specific width using a unit like dp (density-independent
pixels), for example 100dp.

android:layout_height="wrap_content" : Similar to layout_width, this attribute defines the height of the


view. It can take the same values as layout_width
48
EDITTEXT
❑ EditText allows users to input and edit text. It’s commonly used for forms, login screens, etc. You
can customize its appearance and behavior using various attributes such as inputType, hint, and
maxLength.
<EditText <EditText
android:id="@+id/editText" android:id="@+id/passwordEditText"
android:layout_width="342dp" android:layout_width="289dp"
android:layout_height="33dp" android:layout_height="45dp"
android:hint="Enter your name" android:hint="Enter password"
android:inputType="text" android:inputType="textPassword"
tools:layout_editor_absoluteX="34dp" tools:layout_editor_absoluteX="61dp"
tools:layout_editor_absoluteY="92dp" /> tools:layout_editor_absoluteY="173dp" />

❑ Explanation:
android:hint="Enter your name" : This shows a prompt when the field is empty .

android:inputType="text" ": This specifies that the input should be plain text (i.e., no special
formatting).

android:inputType="textPassword“ : This will hide the password characters as they are typed. 49
EDITTEXT
❑ To retrieve the text value from an EditText :

// ///////java code
EditText editText = findViewById(R.id.myEditText);
String textValue = editText.getText().toString(); // Get the text and convert to String

• findViewById(R.id.myEditText) finds the EditText by its ID in the layout.


• getText() retrieves the text as an Editable object.
• toString() converts the Editable object into a regular string.

50
BUTTON
❑ Button is a clickable UI element. It can trigger actions when clicked, such as navigating to another
screen, submitting a form, etc.

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />

❑ It is possible to adjust the spacing of views:


•Padding: Space between the text and the edges, managed by each view.
•Margin: Space around the edges, managed by the parent layout.

51
BUTTON(EVENT LISTENER)
❑ When handling a button click event in Android, we use an event listener. This is an object that "listens"
for user actions and executes specific code when triggered.

❑ To handle button clicks in Android Studio using Java, we use the setOnClickListener method.

❑ In Android, View.OnClickListener is a predefined interface that forces the implementation of the


onClick(View v) method. This method defines what should happen when a view (like a button) is clicked.

❑ Ways to Implement View.OnClickListener interface:

1️⃣ Using a Separate Inner Class (Better Structure)

2️⃣ Using an Anonymous Inner Class (Temporary, defined inside setOnClickListener)

3️⃣ Using a Lambda

52
BUTTON(1️⃣USING A SEPARATE INNER CLASS)
❑ The setOnClickListener method accepts an object that implements View.OnClickListener interface. So, we
have to create a separate inner class that implements View.OnClickListener. After that, we define what happens
when the button is clicked (inside the onClick() method), and finally, we create an instance of this class and
pass it to the setOnClickListener method.
public class MainActivity extends AppCompatActivity { 3
Button button = findViewById(R.id.button);
1
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
2 button.setOnClickListener(new MyClickListener());}
/////////// this a separate inner class
public class MyClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Button Clicked!", Toast.LENGTH_SHORT).show();}}
•The onClick(View v) }
method is called when the
user clicks the button.
Reusable in multiple places
More code 53
BUTTON (2️⃣USING AN ANONYMOUS INNER CLASS)
❑ Question : What is an Anonymous Inner Class?

❑ Answer : An anonymous inner class is a class that does not have a name. It is used to create a one-
time-use object of a class without explicitly defining a separate class.In Android, we often use an
anonymous inner class to implement event listeners, such as View.OnClickListener.

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but=(Button)findViewById(R.id.button);
but.setOnClickListener(new View.OnClickListener(){ @Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "I Love Tunisia", Toast.LENGTH_LONG).show(); }});
}
}

Best for simple actions


Not reusable 54
BUTTON (3️⃣USING A LAMBDA )
❑ Alternative: Using a Lambda (Shorter Code in Java 8+) .
For a simpler way to write the same click event (if you are using Java 8 or Kotlin),
you can use a lambda function:

but.setOnClickListener(v ->
Toast.makeText(getApplicationContext(), "Button clicked!", Toast.LENGTH_SHORT).show()
);

❑ A Lambda Expression is a shorter way to write anonymous classes that implement interfaces
with a single method. In Java, it helps reduce boilerplate code and makes your code cleaner.

Advantage: Less code, easier to read!

55
BUTTON (3️⃣USING A LAMBDA )
❑ v → This is the parameter (View v) representing the button clicked.
❑ -> → This is the lambda arrow, which separates parameters from the function body.
❑ { ... } → The function body, which runs when the button is clicked.
❑ Since setOnClickListener requires a View.OnClickListener (which has only one method:
onClick(View v)), Java automatically understands that our lambda is implementing this
method.
❑ Question : When Can You Use Lambdas?
❑ Answer : You can only use lambda expressions when an interface has only one abstract
method (called a functional interface).

Traditional Anonymous Class Lambda Expression (Java 8+)


More code Less code
Harder to read Easier to read
Creates an extra anonymous class No extra class needed

56
CHECKBOX
❑ CheckBox is a UI element that allows users to select one or more options. It is typically used for
binary choices (checked/unchecked).
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I agree to the terms and conditions" />

❑ In the Java code, you can check if the CheckBox is checked:


We can check if a CheckBox
CheckBox myCheckBox = findViewById(R.id.checkBox); is checked or not using the
isChecked() method.
if (myCheckBox.isChecked()) {
// Checkbox is checked
Toast.makeText(this, "Checkbox is checked!", Toast.LENGTH_SHORT).show();
} else {
// Checkbox is not checked
Toast.makeText(this, "Checkbox is not checked!", Toast.LENGTH_SHORT).show();
}
57
RADIOBUTTON AND RADIOGROUP
❑ RadioButton allows the user to select one option from a group of choices. RadioGroup is used to
group RadioButton elements, ensuring that only one option can be selected at a time.

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2" />
</RadioGroup>
58
RADIOBUTTON AND RADIOGROUP
❑ In Java, you can check which RadioButton is selected:

radioButtonCelsiusToFahrenheit = findViewById(R.id.radio_celsius_to_fahrenheit);
if (radioButtonCelsiusToFahrenheit.isChecked()) {
// action here
}

isChecked(): This checks whether each RadioButton is checked.

59
ACTIVITY LIFECYCLE
Question : What is the Activity Lifecycle?

An Activity in Android goes through multiple stages from creation to destruction. The Android
system automatically calls lifecycle methods to manage how an Activity behaves during:

• App launch
• User interactions (switching between screens, rotating the phone, pressing
home/back buttons, etc.)
• App closing

60
ACTIVITY LIFECYCLE
❑ When an Activity is created and used, it passes through several states. Here are the 7 core lifecycle
methods:
Method When is it called? What happens?
UI is initialized, variables are set
onCreate() When the Activity is created
up
Activity is visible but not yet
onStart() When the Activity becomes visible
interactive
User can now interact (click
onResume() When the Activity is interactive
buttons, type, etc.)
Temporary pause (e.g., user
onPause() When the Activity is partially hidden opens a notification) . Activity is
still running, but it is losing focus
Activity is fully hidden (another
onStop() When the Activity is no longer visible
activity is open)
When the Activity is removed from Activity is shut down and
onDestroy()
memory resources are released
When the Activity is restarted after being Activity returns from onStop() to 61
onRestart()
stopped onStart()
ACTIVITY LIFECYCLE
❑ Question : Where do these methods come from?
❑ Answer : Activity is a built-in class in Android that provides these lifecycle methods.
Your activity class (e.g., MainActivity) inherits from AppCompatActivity, which itself extends
Activity.

Hierarchy

Activity (Base class for all activities)

AppCompatActivity (Adds support for modern UI features)

Your Activity (e.g., MainActivity)

62
ACTIVITY LIFECYCLE
❑ Question : Who calls these lifecycle methods?
❑ Answer : You don’t call them manually.The Android system automatically calls them when
the activity state changes.

Example:
• When you open an activity → Android calls onCreate() , onStart() , onResume() .
• When you press home button → Android calls onPause() , onStop() .
• When the activity is destroyed → Android calls onDestroy().

63
ACTIVITY LIFECYCLE

64
WHAT IS AN INTENT?
❑ An Intent is a messaging object used to communicate between different components of an
Android app.
❑ Think of it as a way to request an action from another component (activity, service, or
broadcast receiver).

❑ Question : Why Do We Use Intents?


❑ Answer : We use Intents to:
Navigate from one activity to another.
Send data between activities.
Start system apps (e.g., open a web browser, make a call).
Broadcast messages (e.g., notify when battery is low).
Start services (e.g., playing music in the background).

65
TYPES OF INTENTS
❑ There are two types of intents in
Android:

Type Description
❑ Think of Explicit Intent in Android like taking a bus that
goes to a specific destination.
❑ Imagine you are at a bus station (your current activity) and
Explicit Intent you want to go to your friend's house (another activity). You
take a direct bus that goes only to your friend’s house
(specific activity).
❑ Used to start a specific activity within the same app.
❑ An implicit intent in Android is like taking any available
bus that goes to a place that offers the service you need,
without specifying a particular bus number. Instead of telling
the system exactly which activity to open, you just say what
Implicit Intent
kind of action you want to perform, and Android finds the
best app for it.
❑ Used to request an action from another app (e.g., opening
a web page, making a call). 66
EXPLICIT INTENT
❑ Example: Navigating from MainActivity to SecondActivity Defines an intent to go from
MainActivity to SecondActivity.

// java code here of MainActivity


Button btn = findViewById(R.id.button);
The startActivity()
btn.setOnClickListener(v -> {
method in Android
Intent i = new Intent( MainActivity.this , SecondActivity.class );
is used to start a
startActivity(i) ;
new activity.
});

MainActivity.this: Refers to the current


activity (the activity from where you are
launching the new one). SecondActivity.class: The class of
the activity that you want to open.

67
EXPLICIT INTENT WITH DATA TRANSFER
Step 1: Sending Data from MainActivity
• data (Various types) → The
❑ Example: Sending Data to Another Activity actual data to send (String, int,
boolean, etc.)
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent. putExtra (“isitcom“ , "Hello from MainActivity!");
startActivity(intent); • key (String) → A unique
name (identifier) for the data.

putExtra() is a method used in Intents to send


extra data from one component (Activity,
Service, BroadcastReceiver) to another.

What Happens Here?


We create an Intent to go from MainActivity to SecondActivity.
We add extra data using putExtra("message", "Hello from MainActivity!");
We start the new activity using startActivity(intent);

68
EXPLICIT INTENT WITH DATA TRANSFER
Step 2: Receiving Data in SecondActivity
• getStringExtra("key") → Gets a
string value from the intent.
TextView textView = findViewById(R.id.textView);
// Retrieving the data sent from MainActivity
String message = getIntent() . getStringExtra("isitcom") ;
// Displaying the received message in TextView
textView.setText(message); getIntent() → Retrieves the intent that
setText(message) → Displays the started the activity.
received message in a TextView.

What Happens If the Key Doesn't Exist?


If “isitcom" is not found, the app may show null or crash. To prevent
this, we can provide a default value:
String message = getIntent().getStringExtra("good morning");
if (message == null) {message = "No message received";}
textView.setText(message);
69
This ensures the app never crashes even if no data is passed.
IMPLICIT INTENT (OPENING SYSTEM APPS)
Example 1: Open a Web Page
Intent.ACTION_VIEW → Requests to view a URL.

Intent intent = new Intent( Intent.ACTION_VIEW );


intent. setData(Uri.parse("https://www.google.com"));
startActivity(intent);

setData(Uri.parse("https://www.google.com"))
→ Passes the website URL.

startActivity(intent); → Opens the web browser.

70
IMPLICIT INTENT (OPENING SYSTEM APPS)
Example 2: Open the Dialer with a Phone Number

Intent.ACTION_DIAL → Opens the dialer with a given number.

Intent intent = new Intent( Intent.ACTION_DIAL );


intent.setData(Uri.parse("tel:+21612345678"));
startActivity(intent);

71
IMPLICIT INTENT (OPENING SYSTEM APPS)
Example 3: Send an Email

72
IMPLICIT INTENT (OPENING SYSTEM APPS)
Example 4: Open Camera to Take a Picture

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);


startActivity(intent);

MediaStore.ACTION_IMAGE_CAPTURE → Opens the camera

73
HOW TO STOP THE CURRENT ACTIVITY ?
❑ Stopping an activity means closing the current screen and removing it from the activity stack.
❑ The most common way to stop an activity is using finish() .

// java code here //


Button exitButton = findViewById(R.id.exitButton);
exitButton.setOnClickListener(v -> finish() ); // Close this activity

Question : What happens?

Answer : When the button is clicked, finish() removes the current activity from memory.
If there was a previous activity, it will be shown.

74
HOW TO STOP THE CURRENT ACTIVITY ?
❑ If we open a new activity and don’t want the user to come back, we call finish() after starting
the new activity:

Intent intent = new Intent(MainActivity.this, SecondActivity.class);


startActivity(intent);
finish(); // Close MainActivity

Question : What happens?

Answer : MainActivity is stopped and removed.


The user cannot go back to MainActivity by pressing the Back button.

75
HOW TO STOP THE CURRENT ACTIVITY ?
When we call finish() , the system automatically triggers the lifecycle methods in this order:
1️⃣ onPause() → The activity is partially visible but about to be stopped.
2️⃣ onStop() → The activity is completely hidden.
3️⃣ onDestroy() → The activity is permanently destroyed and removed from memory.

We can test this behavior by adding Toast inside each lifecycle method :

Button btnClose = findViewById(R.id.button3);


btnClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {Toast.makeText(MainActivity.this,"call finish",Toast.LENGTH_SHORT).show(); finish();}});
@Override
protected void onPause() {super.onPause();
Toast.makeText(MainActivity.this,"pause",Toast.LENGTH_SHORT).show();}
@Override
protected void onStop() {super.onStop();
Toast.makeText(MainActivity.this,"stop",Toast.LENGTH_SHORT).show();}
@Override
protected void onDestroy() {super.onDestroy();
Toast.makeText(MainActivity.this,"destroy",Toast.LENGTH_SHORT).show();} 76
HOW TO STOP THE CURRENT ACTIVITY ?
❑ If we want to stop an activity after a few seconds, we can use a Handler

new Handler().postDelayed(() -> finish(), 5000); // Stops activity after 5 seconds

77
STOPPING THE ENTIRE APPLICATION ?
❑ Using finishAffinity()
❑ Closes all activities in the same task (same app stack).
❑ If the app has multiple activities, it will close all of them and exit the app.
❑ Useful for logging out or when you want to exit the entire app.

Button b = findViewById(R.id.btnbyebye);
b.setOnClickListener(v -> finishAffinity() );

Question : What happens?


Asnwer : All opened activities in the app are closed, and the app is exited.

Question : Does finishAffinity() Completely Exit the App?


Asnwer :
No! The app might still be running in memory (e.g., background services).
But Yes, all UI activities are removed, and the user sees the home screen.

78
SUMMARY FINISH() VS FINISHAFFINITY()

Method Effect
finish() Closes the current activity
finishAffinity() Closes all activities in the app

79
WHAT IS VIEWBINDING?
❑ ViewBinding is a feature in Android that helps you easily access views from your layout XML in a type-
safe and simple way without writing findViewById().

Before ViewBinding (Old Way): You had to write:

TextView myText = findViewById(R.id.my_text);


myText.setText("Hello");

This is:
•Error-prone (you might reference the wrong ID).
•Verbose (you repeat a lot of code).

80
WHAT IS VIEWBINDING?
How to Enable ViewBinding ?
Open your build.gradle (Module: app) and make sure you have this:
android
{
………..
buildFeatures {
viewBinding = true
}
}

Then click "Sync Now" in Android Studio.

81
WHAT IS VIEWBINDING?
❑ If your XML is named hello_world.xml, the generated binding would be: HelloWorldBinding

XML file name Generated class


dialog_perso.xml DialogPersoBinding
my_dialog.xml MyDialogBinding
dialog_user_input.xml DialogUserInputBinding

Naming rule:
dialog_perso.xml → class name becomes DialogPersoBinding.

❑ When ViewBinding is enabled, Android Studio generates a binding class for each XML layout file.

❑ So, if you have: res/layout/activity_main.xml ViewBinding will generate a class called:


ActivityMainBinding

82
WHAT IS VIEWBINDING?
With ViewBinding (Modern Way): •This method creates an object of type
DialogPersoBinding and inflates (i.e. converts)
•It's an auto-generated the XML layout into actual View objects in
class by Android's memory.
ViewBinding feature. •It uses the LayoutInflater, which is responsible
•It represents the layout for turning XML into real UI views.
file dialog_perso.xml.
ActivityMainBinding binding = ActivityMainBinding . inflate ( getLayoutInflater() );
•The getRoot() method setContentView(binding . getRoot() );
of a ViewBinding object binding.myText.setText("Hello");
returns the top-level view
of the layout. •This method is available in
•It's the actual View that Activities and Contexts.
was inflated from XML. •It returns a LayoutInflater
•In our case, it returns the object, which Android uses
root LinearLayout (or internally to convert XML
whatever root view you layouts into Java objects.
defined in
dialog_perso.xml).
83
WHAT IS AN ALERTDIALOG?
❑ An AlertDialog is a small pop-up window used to show messages, ask for confirmation, or get
user input. It usually appears in the center of the screen with buttons like "OK", "Cancel", or
"Yes (PositiveButton) / No (NegativeButton)".

❑ Why Use AlertDialog :


•To warn the user (e.g., "Do you want to delete this file?").
•To ask for confirmation (e.g., "Are you sure you want to exit?").
•To get input from the user (e.g., a text field for entering a name).

84
WHAT IS AN ALERTDIALOG?
// Step 1: Find the button and set a click listener
Button button = findViewById(R.id.button2);
button.setOnClickListener(v -> {
// Step 2: Create an AlertDialog Builder
new AlertDialog.Builder(MainActivity.this)
.setTitle("Exit Confirmation") // Step 3: Set title of dialog
.setMessage("Are you sure you want to exit?") // Step 4: Set message
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish(); // Step 5: Close the activity (exit the app)
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); // Step 6: Close the dialog (cancel)
}
})
.show(); // Step 7: Show the dialog }); 85
CREATE A CUSTOM DIALOG
Why use a custom dialog?
Sometimes, you need to ask the user for more complex information — like a name, an email, or a message but
you don’t want to open a new screen (new Activity).
In this case, we can use a custom dialog, which is a small popup window with our own design and logic.

Creating a Custom Dialog


To create a custom dialog, we must first define a layout XML that contains all the necessary UI elements
(like TextView, EditText, and Button).

Note:
The dialog title is not defined in the layout — it is set separately.
We must include at least one validation button (e.g., “OK” or “Submit”).Canceling is optional
because the user can dismiss the dialog with the system back button.

86
CREATE A CUSTOM DIALOG
Step 1: Enable ViewBinding in your project
ViewBinding allows you to connect your layout XML directly to Java code without findViewById().

android
{
………..
buildFeatures {
viewBinding = true
}
}

Then sync your project.

87
CREATE A CUSTOM DIALOG
Step 2: Create a custom XML layout
res/layout/dialog_perso.xml

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" <EditText
android:padding="20dp" android:id="@+id/libelle"
android:layout_width="wrap_content" android:hint="Type name"
android:layout_height="wrap_content"> android:layout_width="wrap_content"
<TextView android:layout_height="wrap_content" />
android:id="@+id/title" <Button
android:layout_width="wrap_content" android:id="@+id/valider"
android:layout_height="wrap_content" android:text="Validate"
android:text="Ttile" android:layout_width="wrap_content"
android:textSize="20sp" android:layout_height="wrap_content" />
android:textStyle="bold" </LinearLayout>
android:gravity="center" />
88
CREATE A CUSTOM DIALOG
Step 3: Load and show the dialog in Java
In your MainActivity.java:
// 1. Create the Dialog
Dialog dialog = new Dialog(MainActivity.this);
// 2. Inflate the layout using ViewBinding
DialogPersoBinding dialogUI = DialogPersoBinding. inflate ( getLayoutInflater() );
// 3. Set the custom layout as content view
dialog.setContentView(dialogUI. getRoot() );
// 4. Handle the validate button
dialogUI.valider.setOnClickListener(v -> {
// Retrieve user input
String value = dialogUI.libelle.getText().toString();
// Process input (for example, show a Toast)
Toast.makeText(this, "You typed: " + value, Toast.LENGTH_SHORT).show();
// Close the dialog
dialog.dismiss(); });
dialog.show();

89
DIALOG VS ALERTDIALOG
Feature Dialog (Base Class) AlertDialog (Subclass)
The generic class for A ready-to-use dialog for
What is it?
creating dialogs common cases
Fully customizable (you Less customizable but has
Customizable?
define layout, etc.) built-in features
Has built-in
Has Buttons? No default buttons positive/negative/neutral
buttons
Easier to use for simple
Requires more work (custom
Ease of Use confirmation/message
layout etc.)
popups
Complex UI (e.g. login form, Simple alerts, messages,
Use Case
custom layout) confirmations (Yes/No/OK)

90
WHAT IS ERGONOMICS IN ANDROID APPS?
❑ Ergonomics refers to how user-friendly an app is.
❑ It means designing the app in a way that:
•Makes it easy to understand
•Makes it comfortable to use
•Reduces the user’s effort to achieve tasks
•Works well on different devices

91
ACTION BAR(TOOLBAR)
❑ The Action Bar, now commonly referred to as the App Bar, is a fundamental component in
Android applications. It provides a dedicated space at the top of the screen for branding,
navigation, and actions.

❑ Components of the Action Bar:


1.App Icon/ Title : Represents the application branding. Displays the current activity or
screen title.
2.Action Buttons: Key actions for the current context.
3.Overflow Menu: Houses additional actions that don't fit in the main action bar.

92
WHAT IS A MENU IN ANDROID?
❑ A menu in Android is a way to give the user options to perform actions, like "Settings",
"Search", "Logout", etc.

93
CREATING AN OPTIONS MENU IN ANDROID
❑ Example : We’ll create a menu with two options:
• Settings
• Help

Step 1: Create a Menu XML File


In Android, menus are usually defined in XML (like layouts).
Go to: res/menu/ (create the folder if it doesn't exist)
Create a new file: main_menu.xml <menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
app:showAsAction controls where your
<item
menu item appears either directly on
android:id="@+id/action_search"
the toolbar (action bar) or inside the
android:title="Search"
overflow menu (three dots).
android:icon="@android:drawable/ic_menu_search"
• ifRoom : Show on toolbar if there’s
app:showAsAction ="ifRoom" />
space; otherwise overflow menu
<item
• Never : Always show in overflow
android:id="@+id/action_settings"
menu only
android:title="Settings"
• Always : Always show the item in
android:icon="@android:drawable/ic_menu_preferences"
the action bar (if there's room).
app:showAsAction =“never" />
</menu> 94
CREATING AN OPTIONS MENU IN ANDROID
Step 2: Inflate the menu in the activity
In your MainActivity.java , override onCreateOptionsMenu() :

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the app bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

95
CREATING AN OPTIONS MENU IN ANDROID
Step 3: Handle clicks in onOptionsItemSelected()

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
super.onOptionsItemSelected(item) :
if (item.getItemId() == R.id.action_settings) {
If the selected item is not one of the
// Handle settings item click
ones I handled, then let the parent
Toast.makeText(this, "Settings clicked", Toast.LENGTH_SHORT).show();
class handle it (like system-defined
return true;
items, back arrow, etc.).
} else if (item.getItemId() == R.id.action_search) {
// Handle search item click
Toast.makeText(this, "Search clicked", Toast.LENGTH_SHORT).show();
return true;
} else {
return super.onOptionsItemSelected(item) ;
}
}

96
CREATING AN OPTIONS MENU IN ANDROID
Question : how to add menu items manually in Java (instead of XML) ?

@Override
What do the parameters mean? public boolean onCreateOptionsMenu(Menu menu) {
menu.add(groupId, itemId, order, title) // Add a menu item programmatically
menu.add(Menu.NONE, 1, Menu.NONE, "Help")
• groupId: Usually Menu.NONE, unless .setIcon(android.R.drawable.ic_menu_help)
you group items. .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
•itemId: An integer that uniquely identifies menu.add(Menu.NONE, 2, Menu.NONE, "About")
the item. .setIcon(android.R.drawable.ic_menu_info_details)
•order: The order of appearance in the .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu (use Menu.NONE if not needed). return true;
•title: The text to display. }
CREATING AN OPTIONS MENU IN ANDROID

Run the app

Problem: Why Is the Menu Not Showing?


Sometimes the menu doesn’t show at all. That’s
because your activity needs an Action Bar to
display the menu.

98
CREATING AN OPTIONS MENU IN ANDROID
Solution 1
Use a theme that supports Action Bar Delete this
Open: res/values/themes.xml and themes.xml(night)
And change this old code :
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Base.Theme.MyApplication" parent="Theme.Material3.DayNight. NoActionBar ">
<!-- Customize your light theme here. --> </style>
<style name="Theme.MyApplication" parent="Base.Theme.MyApplication" /></resources>

To this :
<resources xmlns:tools="http://schemas.android.com/tools">
<style name="Base.Theme. MyApplication " parent="Theme.Material3. DayNight">
<!-- Customize your light theme here. -->
</style>
<style name="Theme.MyApplication" parent="Base.Theme.MyApplication" /></resources>

Notice : Make sure your AndroidManifest.xml uses this theme MyApplication :


android:theme="@style/Theme. MyApplication " 99
CREATING AN OPTIONS MENU IN ANDROID
Solution 2
Manually add a Toolbar In your layout file (activity_main.xml) , Place this at the top of your layout :

<androidx.appcompat.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:title="My App"
app:titleTextColor="@android:color/white" />

100
CREATING AN OPTIONS MENU IN ANDROID
Solution 2
In MainActivity.java , add this in onCreate()

Toolbar toolbar = findViewById(R.id.my_toolbar);


setSupportActionBar(toolbar); // This shows the menu

Run the app

101
CREATING AN OPTIONS MENU IN ANDROID

Option Description Menu Visible?


Change to Theme with
ActionBar Easy solution for beginners Yes
(Theme.Material3.DayNight)
Use NoActionBar + Manual control, more
Yes
Toolbar customizable
Keep NoActionBar without
The menu won't be visible No
Toolbar

102
WHAT IS A CASCADING MENU (SUBMENU)?
❑ A cascading menu in Android is when you click on a menu item and a submenu opens with more
options.

103
WHAT IS A CASCADING MENU (SUBMENU)?
❑ Create the Menu XML File in res/menu/main_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_file"
android:title="File">
<!-- Submenu inside -->
<menu>
<item
android:id="@+id/menu_new"
android:title="New" />
<item
android:id="@+id/menu_open"
android:title="Open" />
</menu> </item>
<item
android:id="@+id/menu_settings"
android:title="Settings"
app:showAsAction="never" /> </menu> 104
WHAT IS RECYCLERVIEW?
❑ RecyclerView is a powerful list UI component in Android used to display large sets of data efficiently.

❑ We want to develop an Android app that displays and edits a list of items.

❑ The screen is mainly occupied by a RecyclerView, which is a specialized view for displaying long or
complex lists efficiently.

❑ Why RecyclerView? Before, we used ListView, but it's now outdated because:
• It lacks flexibility
• It’s not memory efficient
• It doesn’t support animations or complex layouts easily

105
WHAT IS RECYCLERVIEW?
❑ Step 1 – Create the Data Class
We start by creating a simple class called Movie to represent the data:

public class Cinema {


private String title;
private int year;
public Cinema(String title, int year) {
this.title = title;
this.year = year;
}
// getters & setters
}

106
WHAT IS RECYCLERVIEW?
❑ Step 2 – Create Initial Data
You can initialize the list in two ways:

Option 1: (Better): From resources : Option 2: Hardcoded Java ArrayList in


Create arrays in res/values/arrays.xml MainActivity.java file :

<resources> private ArrayList<Cinema> liste;


<string-array name="titles"> liste = new ArrayList<>();
<item>Inception</item> liste.add(new Cinema(" Interstellar ",2014));
<item>Interstellar</item> liste.add(new Cinema(“Breaking Bad",2008));
<item>The Dark Knight</item></string-array> liste.add(new Cinema(“Better Call Saul",2008));
<integer-array name="years"> liste.add(new Cinema(“Game Of Thrones",2011));
<item>2010</item>
<item>2014</item>
<item>2008</item></integer-array></resources>

107
WHAT IS RECYCLERVIEW?
❑ Step 3 – Design the Layout with RecyclerView

In your activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
▪ The RecyclerView fills the
android:layout_height="match_parent">
whole screen.
<androidx.recyclerview.widget.RecyclerView
▪ You can add buttons and
android:id="@+id/recycler"
other views later if
android:layout_width="match_parent"
needed.
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout> 108
WHAT IS RECYCLERVIEW?
❑ Step 4 – Create Row Layout item_cinema.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="@+id/year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp" />
</LinearLayout> 109
WHAT IS RECYCLERVIEW?
❑ Step 5 – Create the Adapter CinemaAdapter.java
Question : What is an Adapter in Android?
In Android, an Adapter is a bridge between a data source (like an ArrayList) and a UI component (like
a RecyclerView, ListView, or GridView).It takes your data (like a list of movies) and adapts it into views
that can be displayed on the screen.
❑ When using a RecyclerView, we must create our own Adapter by extending RecyclerView.Adapter.
Here’s what you do:
public class CinemaAdapter extends RecyclerView.Adapter< CinemaAdapter. CinemaViewHolder > {
////// code }

110
WHAT IS RECYCLERVIEW?
❑ Step 5 – Create the Adapter CinemaAdapter.java
public class CinemaAdapter extends RecyclerView.Adapter<CinemaAdapter.CinemaViewHolder> {
private List<Cinema> cinemaList;
• Called only when needed to create a new row
// constructor
(item).
public CinemaAdapter(List<Cinema> cinemas) {
• item_cinema.xml is your layout for each item.
this.cinemaList = cinemas; }
• We inflate this layout and create a ViewHolder
@NonNull
to hold it.
@Override
public CinemaViewHolder onCreateViewHolder (@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cinema, parent, false);
return new CinemaViewHolder(view); }
@Override
public void onBindViewHolder (@NonNull CinemaViewHolder holder, int position) {
Cinema m = cinemaList.get(position);
holder.title.setText(m.title); • This method is called to fill the views with data.
holder.year.setText(String.valueOf(m.year)); • It’s like saying: “At position i, show this title and this
} year.”
• holder.title and holder.year refer to TextViews
111
defined in the ViewHolder.
WHAT IS RECYCLERVIEW?
❑ Step 5 – Create the Adapter CinemaAdapter.java ( rest of the code)

@Override
• Returns the total public int getItemCount() {
number of items in return cinemaList.size();
your data list. }
• This lets RecyclerView
know how many items public static class CinemaViewHolder extends RecyclerView.ViewHolder {
to draw. TextView title, year;
public CinemaViewHolder(@NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title);
This class holds the references year = itemView.findViewById(R.id.year);
to the views in each row (like }
TextView) }
}

112
WHAT IS RECYCLERVIEW?
❑ Step 6 – Setup RecyclerView public class MainActivity extends AppCompatActivity {
in MainActivity.java private ActivityMainBinding ui;
(using Option 1) private ArrayList<Cinema> liste;
private CinemaAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ui = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(ui.getRoot());
Resources res = getResources();
String[] titles = res.getStringArray(R.array.titles);
int[] years = res.getIntArray(R.array.years);
liste = new ArrayList<>();
for (int i = 0; i < titles.length; i++) {
liste.add(new Cinema(titles[i], years[i]));
}
adapter = new CinemaAdapter(liste);
ui.recycler.setLayoutManager(new LinearLayoutManager(this));
ui.recycler.setAdapter(adapter);
}} 113
WHAT IS RECYCLERVIEW?
❑ Step 6 – Setup RecyclerView public class MainActivity extends AppCompatActivity {
in MainActivity.java private ActivityMainBinding ui;
(using Option 2) private ArrayList< Cinema > liste;
private CinemaAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ui = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(ui.getRoot());
liste = new ArrayList<>();
liste.add(new Cinema("Inception",2010));
liste.add(new Cinema("Interstellar",2014));
liste.add(new Cinema("The Dark Knight",2008));
liste.add(new Cinema("Tenet",2020));
adapter = new Cinema Adapter(liste);
ui.recycler.setLayoutManager(new LinearLayoutManager(this));
ui.recycler.setAdapter(adapter);
}
}
114
WHAT IS RECYCLERVIEW?
Run the app
(using Option 1) (using Option 2)

115
WHAT IS A CONTEXT MENU?
❑ A Contextual Menu (in French: menu contextuel) is a menu that appears when the user long-presses
(or right-clicks in other systems) on a View like a TextView, ListView item, or ImageView.
❑ It allows the user to choose actions related to that specific item.
Example: Long press on a message in WhatsApp → options like Reply, Delete, Forward.
❑ list UI component in Android used to display large sets of data efficiently.

116
WHAT IS A CONTEXT MENU?
<?xml version="1.0" encoding="utf-8"?>
Step 1. XML Layout (activity_main.xml) <androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="132dp"
android:layout_marginTop="100dp"
android:text="Long press me"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout> 117
WHAT IS A CONTEXT MENU?
Step 2. Create the Menu XML (res/menu/context_menu.xml)

<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_edit"
android:title="Edit" />
<item android:id="@+id/action_delete"
android:title="Delete" />
</menu>

118
WHAT IS A CONTEXT MENU?
Step 3. Java Code (MainActivity.java)
public class MainActivity extends AppCompatActivity { TextView myTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTextView = findViewById(R.id.myTextView);
// Register the view for context menu Inflate the context menu
registerForContextMenu(myTextView); }
@Override
public void onCreateContextMenu (ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.context_menu, menu); }
Handle clicks
@Override
public boolean onContextItemSelected (@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_edit) {Toast.makeText(this, "Edit selected", Toast.LENGTH_SHORT).show();return true;}
else if (id == R.id.action_delete) {Toast.makeText(this, "Delete selected", Toast.LENGTH_SHORT).show();return true;}
else {return super.onContextItemSelected(item); } } } 119
WHAT IS A FRAGMENT IN ANDROID?
❑ A Fragment in Android represents a reusable portion of the UI in an Activity. Think of a Fragment as a
modular section of an Activity that has its own lifecycle, layout, and logic.
•Introduced to support flexible UI on devices with different screen sizes (phones, tablets).
•A single Activity can contain multiple Fragments.
•Fragments must be hosted inside an Activity.

❑ Why Use Fragments?


1.To reuse UI across multiple activities or screen sizes (phones vs tablets)
2.Dynamic and flexible UIs.
3.Separate logic for different parts of UI.

❑ You can think of it as: A piece of the screen that has its own layout(xml), its own logic(java), and
can be added or removed from an Activity.

120
WHAT IS A FRAGMENT IN ANDROID?
❑ Real-life analogy:
Imagine an Activity is like a full webpage, and Fragments are like reusable components (e.g., a navigation
bar, a chat window, a product detail panel). You can reuse or replace parts of the page dynamically using
fragments.

❑ Examples of fragments:
•Displaying a list of items
•Showing details of a selected item
•Form for editing an item

❑ Fragments provide flexibility and


allow you to combine multiple
smaller UI components to form a
complete UI. In modern Android
development, fragments are
essential for building responsive
UIs, especially for tablets and
phones with varying screen sizes.
121
WHAT IS A FRAGMENT IN ANDROID?
❑ Basic Fragment Structure in Android
• In Android, a fragment must be a part of an activity. On its own, a fragment is not capable of being
displayed.
• A fragment is tied to the activity, and you need to create and configure the fragment’s layout,
behavior, and lifecycle.

public class InfosFragment extends Fragment {


public InfosFragment() {} // Mandatory constructor
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflating the fragment layout
View rootView = inflater.inflate(R.layout.fragment_infos, container, false);
// Setup views, listeners, adapters, etc.
// Example: TextView textView = rootView.findViewById(R.id.textView);
return rootView; // Return the root view of the fragment
}
}

onCreateView() is called when it's time to


create the UI 122
WHAT IS A FRAGMENT IN ANDROID?
❑ Fragment with Adapter
Here is an example of a fragment that uses an adapter to populate a list of items, such as a list of films:

public class ListeFragment extends Fragment { private List<Film> liste; private FilmAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the fragment layout
View rootView = inflater.inflate(R.layout.fragment_liste, container, false);
// Example: Fetch data (from a database, API, etc.)
liste = fetchFilms ();
// Create and set the adapter
adapter = new FilmAdapter(liste);
// Set up RecyclerView or ListView
RecyclerView recyclerView = rootView.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter); return rootView; }
private List<Film> fetchFilms() {
// Simulate fetching data (could be from a database or API)
List<Film> films = new ArrayList<>();films.add(new Film("Interstellar",2000));films.add(new Film("Titanic",1997));
return films; } } 123
WHAT IS A FRAGMENT IN ANDROID?
❑ A fragment cannot be displayed on its own; it must be part of an activity, like an internal view. There are
two main ways to work with fragments:

1️⃣ Static Integration :


The fragment is defined in the activity's layout XML, and it stays fixed. This is the simplest method and is
used when the layout doesn't change often.

2️⃣ Dynamic Integration :


Fragments are added, removed, or replaced during runtime based on need. This offers more flexibility
but is more complex to implement.

❑ When to Use Each Method ?


•Use Static when the layout is fixed and doesn't need frequent changes.
•Use Dynamic for flexible, interactive interfaces that require changing fragments at runtime.

124
WHAT IS A FRAGMENT IN ANDROID?
1️⃣ Static Integration:

res/layout/activity_profile_fragment.xml java/ProfileFragment.java

<?xml version="1.0" encoding="utf-8"?> public class ProfileFragment extends Fragment {


<FrameLayout public ProfileFragment() {
xmlns:android="http://schemas.android.com/ap // Required empty public constructor
k/res/android" }
android:background="#8BC34A" @Override
android:layout_width="match_parent" public View onCreateView(LayoutInflater inflater,
android:layout_height="match_parent"> ViewGroup container,
<TextView Bundle savedInstanceState) {
android:text="This is Fragment Two" return
android:textSize="24sp" inflater.inflate(R.layout.activity_profile_fragment,
android:textColor="#FFFFFF" container, false);
android:layout_gravity="center" }
android:layout_width="wrap_content" }
android:layout_height="wrap_content" />
</FrameLayout>
125
WHAT IS A FRAGMENT IN ANDROID?
1️⃣ Static Integration:

res/layout/activity_home_fragment.xml java/HomeFragment.java

<LinearLayout public class HomeFragment extends Fragment {


xmlns:android="http://schemas.android.com/apk public HomeFragment() {
/res/android" // Required empty public constructor
android:orientation="vertical" }
android:gravity="center" @Override
android:layout_width="match_parent" public View onCreateView(LayoutInflater inflater,
android:layout_height="match_parent"> ViewGroup container,
<TextView Bundle savedInstanceState) {
android:text="Welcome to the Home Page!" return
android:textSize="24sp" inflater.inflate(R.layout.activity_home_fragment,
android:layout_width="wrap_content" container, false);
android:layout_height="wrap_content" /> }
</LinearLayout> }

126
WHAT IS A FRAGMENT IN ANDROID?
1️⃣ Static Integration:
res/layout/activity_main.xml java/MainActivity.java

<?xml version="1.0" encoding="utf-8"?> public class MainActivity extends


<LinearLayout AppCompatActivity {
xmlns:android="http://schemas.android.com/apk/res/android" @Override
android:orientation="vertical" protected void onCreate(Bundle
android:layout_width="match_parent" savedInstanceState) {
android:layout_height="match_parent"> super.onCreate(savedInstanceState);
<fragment setContentView(R.layout.activity_main);
android:id="@+id/fragmentOne" // No need to load fragments manually
android:name="com.example.frag.HomeFragment" }
android:layout_width="match_parent" }
android:layout_height="200dp" />
<fragment The full package name + class
android:id="@+id/fragmentTwo" name of the Fragment to create.
android:name="com.example.frag.ProfileFragment" Here, Android will instantiate
android:layout_width="match_parent" ProfileFragment from the
android:layout_height="200dp" com.example.frag
android:layout_marginTop="16dp" /></LinearLayout> 127
WHAT IS A FRAGMENT IN ANDROID?
1️⃣ Static Integration:

Run the app

128
WHAT IS A FRAGMENT IN ANDROID?
2️⃣ Dynamic Integration

res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"android:padding="16dp"android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Buttonandroid:id="@+id/btnFragmentOne"android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load Fragment One" />
<Buttonandroid:id="@+id/btnFragmentTwo"android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load Fragment Two"
android:layout_marginTop="16dp"/>
<FrameLayout
android:id="@+id/fragmentContainer“ android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginTop="20dp"/>
</LinearLayout> 129
WHAT IS A FRAGMENT IN ANDROID?
2️⃣ Dynamic Integration

res/layout/fragment_one.xml java/FragmentOne.java

<?xml version="1.0" encoding="utf-8"?> public class FragmentOne extends Fragment {


<FrameLayout public FragmentOne() {
xmlns:android="http://schemas.android.com/ap // Required empty public constructor
k/res/android" }
android:background="#FFC107" @Override
android:layout_width="match_parent" public View onCreateView(LayoutInflater inflater,
android:layout_height="match_parent"> ViewGroup container,
<TextView Bundle savedInstanceState) {
android:text="This is Fragment One" return inflater.inflate(R.layout.fragment_one,
android:textSize="24sp" container, false);
android:textColor="#000" }
android:layout_gravity="center" }
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
130
WHAT IS A FRAGMENT IN ANDROID?
2️⃣ Dynamic Integration

res/layout/fragment_two.xml java/FragmentTwo.java

<?xml version="1.0" encoding="utf-8"?> public class FragmentTwo extends Fragment {


<FrameLayout public FragmentTwo() {
xmlns:android="http://schemas.android.com/ap // Required empty public constructor
k/res/android" }
android:background="#8BC34A" @Override
android:layout_width="match_parent" public View onCreateView(LayoutInflater inflater,
android:layout_height="match_parent"> ViewGroup container,
<TextView Bundle savedInstanceState) {
android:text="This is Fragment Two" return inflater.inflate(R.layout.fragment_two,
android:textSize="24sp" container, false);
android:textColor="#FFFFFF" }
android:layout_gravity="center" }
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
131
WHAT IS A FRAGMENT IN ANDROID?
2️⃣ Dynamic Integration

java/MainActivity.java

public class MainActivity extends AppCompatActivity { Button btnFragmentOne, btnFragmentTwo;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
btnFragmentOne = findViewById(R.id.btnFragmentOne); btnFragmentTwo = findViewById(R.id.btnFragmentTwo);
btnFragmentOne.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View view) {
loadFragment(new FragmentOne());}});
btnFragmentTwo.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {
loadFragment(new FragmentTwo());}}); }
private void loadFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager(); // Create a FragmentManager
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); // Create a FragmentTransaction
fragmentTransaction.replace(R.id.fragmentContainer, fragment); // Replace the FrameLayout with the new Fragment
fragmentTransaction.addToBackStack(null); // Optional: Add to backstack
fragmentTransaction.commit();}} // Commit the transaction
132
WHAT IS A FRAGMENT IN ANDROID?
2️⃣ Dynamic Integration

Run the app (play the video)

133
WHAT IS A FRAGMENT IN ANDROID?
Handling Orientation Changes (Portrait vs. Landscape)

❑ In Android, you can handle orientation changes by defining separate layouts for different orientations.
❑ Android automatically selects the appropriate layout based on the screen orientation (portrait or
landscape).

1. Portrait Layout (res/layout/activity_main.xml):

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:id="@+id/frag_liste"
android:name="com.example.fragments.ListeFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

134
WHAT IS A FRAGMENT IN ANDROID?
Handling Orientation Changes (Portrait vs. Landscape)

2. Landscape Layout (res/ layout-land /activity_main.xml)


create the folder if it doesn't exist

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
Notice : If you create a folder with a
android:orientation="horizontal" name like “abc” instead of the
android:layout_width="match_parent" conventional layout-land (or other
android:layout_height="match_parent"> standard folder names), Android won't
<fragment android:id="@+id/frag_liste" recognize it automatically.
android:name="com.example.fragments.ListeFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<fragment android:id="@+id/frag_infos"
android:name="com.example.fragments.InfosFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
135
WHAT IS A FRAGMENT IN ANDROID?
Fragment Communication
❑ In some scenarios, you may need to communicate between fragments. For example, if a user clicks on an
item in a list (e.g., a film), you want to display detailed information about that item.
public class MainActivity extends AppCompatActivity implements
getSupportFragmentManager() is a
ListeFragment.OnItemClickListener {
method of the AppCompatActivity class.
// code ……………
When you call it, it returns an object of type
@Override
FragmentManager.
public void onItemClick(ClipData.Item item) {
It’s like a factory or provider that gives you
FragmentManager manager = getSupportFragmentManager() ;
the FragmentManager for this activity.
InfosFragment fragInfos = (InfosFragment)
You need to call it if you want to get access
manager.findFragmentById(R.id.frag_infos);
to the fragment management system.
if (fragInfos != null && fragInfos.isVisible()) {
// If InfosFragment is visible, pass the data to it
fragInfos.displayItemDetails(item);
} else {
// Otherwise, launch a new activity to display the item details FragmentManager is a class in
Intent intent = new Intent(this, InfosActivity.class); Android that is used to manage
intent.putExtra("item", item); (add/remove/replace) fragments
startActivity(intent); } } } within an activity. 136

You might also like