Mobile Dev Final Version
Mobile Dev Final Version
MOBILE DEVELOPMENT
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).
4
WHY MOBILE DEVELOPMENT?
❑ Growing Mobile Market
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!
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 .
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
10
PRINCIPAUX FRAMEWORKS MOBILE
11
MOBILE OS
Why Learn Android?
Conclusion
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.
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.
Le SDK inclut les API, mais les API ne suffisent pas pour développer une app sans le SDK ! 16
ARCHITECTURE D’ANDROID
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 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 :
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.
23
PROJECT STRUCTURE
The general structure of an Android project consists of two main directories:
•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)
25
PROJECT STRUCTURE(1️⃣GRADLE)
1️⃣ What is Gradle?
26
PROJECT STRUCTURE(2️⃣APP DIRECTORY)
• 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.
32
ANDROID RESOURCES
❑ Types of Resources:
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?
❑ 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
// 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
<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:
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.
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.
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 ,…) .
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"
/>
47
TEXTVIEW
❑ Explanation:
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.
❑ 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
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" />
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.
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.
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.
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).
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" />
<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
}
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
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).
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.
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.
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.
setData(Uri.parse("https://www.google.com"))
→ Passes the website URL.
70
IMPLICIT INTENT (OPENING SYSTEM APPS)
Example 2: Open the Dialer with a Phone Number
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
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() .
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:
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 :
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() );
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().
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
}
}
81
WHAT IS VIEWBINDING?
❑ If your XML is named hello_world.xml, the generated binding would be: HelloWorldBinding
Naming rule:
dialog_perso.xml → class name becomes DialogPersoBinding.
❑ When ViewBinding is enabled, Android Studio generates a binding class for each XML layout file.
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)".
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.
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
}
}
87
CREATE A CUSTOM DIALOG
Step 2: Create a custom XML layout
res/layout/dialog_perso.xml
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.
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
@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
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>
<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()
101
CREATING AN OPTIONS MENU IN ANDROID
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:
106
WHAT IS RECYCLERVIEW?
❑ Step 2 – Create Initial Data
You can initialize the list in two ways:
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.
❑ 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
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:
124
WHAT IS A FRAGMENT IN ANDROID?
1️⃣ Static Integration:
res/layout/activity_profile_fragment.xml java/ProfileFragment.java
res/layout/activity_home_fragment.xml java/HomeFragment.java
126
WHAT IS A FRAGMENT IN ANDROID?
1️⃣ Static Integration:
res/layout/activity_main.xml java/MainActivity.java
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
res/layout/fragment_two.xml java/FragmentTwo.java
java/MainActivity.java
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).
<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)
<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