0% found this document useful (0 votes)
10 views80 pages

Mobile Dev (3)

The document provides an overview of mobile development, including definitions of mobile apps, their distribution methods, and the importance of mobile development in today's technology landscape. It discusses various types of mobile applications (native, hybrid, web), challenges faced in mobile development, and key frameworks like React Native and Flutter. Additionally, it covers Android OS, its APIs, SDK, and project structure within Android Studio, emphasizing the significance of XML in defining app layouts.

Uploaded by

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

Mobile Dev (3)

The document provides an overview of mobile development, including definitions of mobile apps, their distribution methods, and the importance of mobile development in today's technology landscape. It discusses various types of mobile applications (native, hybrid, web), challenges faced in mobile development, and key frameworks like React Native and Flutter. Additionally, it covers Android OS, its APIs, SDK, and project structure within Android Studio, emphasizing the significance of XML in defining app layouts.

Uploaded by

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

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),
JavaScript → No need to Native, Flutter → One code
Swift (iOS).
install. for Android & iOS.
✅ Best performance & full
🚀 Examples: Facebook Web, 🚀 Examples: Instagram,
access to phone features
Google Docs online. Twitter, Uber.
(GPS, camera, sensors).
Pros: Easy Pros: Single
🚀 Examples: WhatsApp,
updates, works on any codebase for all platforms.
Instagram, Google Maps.
device. Cons: Not as fast
Pros: Fast & smooth
Cons: Slower & as native apps.
performance.
limited phone feature :
Cons: Expensive →
cannot fully access device
Need separate versions
features like Bluetooth,
for each OS.
sensors.
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
apps (Android & iOS). UI.
🚀 Examples: Instagram, Facebook, Uber 🚀 Examples: Google Ads, BMW App,
Eats. Alibaba.
📌 Advantage: One codebase for Android 📌 Advantage: Performance close to
& iOS. native apps ⚡.
📌 Disadvantage: Less performance 📌 Disadvantage: Requires learning Dart
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:


14
📷 Camera API → Allows taking photos.
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 Ensemble d'outils pour
📌 Définition
pour interagir avec Android développer une application
Classes, méthodes (ex: API + Émulateur + Outils
📂 Contenu
Camera API, Location API) de compilation
Permet d'utiliser des
Permet de créer, tester et
🎯 Utilisation fonctionnalités du
compiler une app
téléphone
LocationManager.getLastKn Android Studio + Debugger
📌 Exemple
ownLocation() + API Android
👉 Le SDK inclut les API, mais les API ne suffisent pas pour développer une app sans le 16
SDK !
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
DÉVELOPPEMENT EN C/C++ AVEC ANDROID
 Avec Android, il est possible d’écrire des applications en C/C++ qui sont exécutées
directement par le système d’exploitation Linux. Pour cela, Android fournit un kit de
développement natif (NDK).
 Kit de Développement Natif (NDK)
Le NDK permet de créer des bibliothèques C++ en utilisant les bibliothèques libc et libm,
offrant un accès natif à OpenGL (Open Graphics Library).
 OpenGL sur Android
OpenGL est une spécification qui définit une API multiplateforme pour la conception
d’applications générant des images 3D ou 2D.

19
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? 20
hl=en
2024-2025

CHAPTER 2 : PROJECT
STRUCTURE

21

Enseignant : Mohamed Hedi


Mahfoudh mohamed.mahfoudh.7@gmail.com
START A NEW ANDROID STUDIO
PROJECT

22
START A NEW ANDROID STUDIO
PROJECT

23
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.

24
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?


4.First-time setup – Android Studio may need to download Gradle files and dependencies.
5.New dependencies – If your project uses external libraries, they are downloaded from the
internet.
25
6.SDK updates – If your chosen MinSDK or Target SDK is not installed, Android Studio will
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.
26
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.

27
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.

28
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
29
classes.
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
android:layout_width="wrap_co does not make it clickable or perform any
ntent" action.
android:layout_height="wrap_c •The Java/Kotlin code handles the button’s 30
ontent"
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:exported="true“ Allows the
android:fullBackupContent="@xml/backup_rules" activity to be accessed by other apps if
android:icon="@mipmap/ic_launcher" needed
android:label="@string/app_name"
An intent-filter inside an <activity> tag tells
android:roundIcon="@mipmap/ic_launcher_round"
the system how this activity should behave
android:supportsRtl="true"
and what types of intents it can handle.
android:theme="@style/Theme.MyApplication"
tools:targetApi="31"> •This defines that this activity is the main entry point of
<activity
the application.
android:name=".MainActivity" •It tells Android that this activity should be launched first
android:exported="true">
when the app starts.
<intent-filter>
<action android:name="android.intent.action.MAIN" />
•This marks the activity as one that should appear in the app
<category android:name="android.intent.category.
</intent-filter> launcher (home screen). 31
</activity> •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, which is a base
AppCompatActivity { class for activities that use the modern
@Override Android components and compatibility
protected void onCreate(Bundle features.
savedInstanceState) {
Bundle savedInstanceState:
super.onCreate(savedInstanceState);
This parameter is used to save
setContentView(R.layout.activity_main);
and restore activity data (e.g., if
}
onCreate: Each activity has multiple lifecycle the device is rotated).
}
methods, which we will discuss later in this This parameter holds the
course. previous state of the activity (if
However, the most important one is the it was paused or restarted).
onCreate method. It is used to set up the It can be null if the activity is
user interface and initialize event listeners for starting
32
user interactions.
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.

33
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.

34
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.

35
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
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.

36
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)
To use this layout in Java:
setContentView(R.layout.activity_ma 37
in);
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
(@+id/myButton) so we can reference
android:layout_width="wrap_cont it in code.
ent"

android:layout_height="wrap_cont
 In Android
ent"
XML layouts, the @+id/myButton notation is used to define a unique identifier for a
UI elementandroid:text="Click
(View) so that it can beMe" />
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)
38
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


// Find the button by ID reference the button defined in the XML
Button myButton = findViewById(R.id.myButton);
layout file.
// 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
// Display a toast message when the buttonclicked
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.

39
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
40
seconds).
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.

41
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>
42
👉 This layout stacks the TextView and Button
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>
43
👉 In this case, Button is positioned below
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="m
atch_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“ 44
👉 Inandroid:text="Button
this example, the buttons
2" are constrained relative to each other and to the
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
45
second button 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.

46
👉 This layout stacks the TextView and Button
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.

47
👉 This layout stacks the TextView and Button
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).

48
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_cont
ent"

android:layout_height="wrap_con
tent"
android:text="winter is
coming"
 We can also change the text dynamically in Java
android:textSize="18sp"
code:
android:textColor="#FF5722"
TextView tvTitre =
/>
findViewById(R.id.tvTitre);
tvTitre.setText(“Say My Name");
49
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


50
height of the view. It can take the same values as layout_width
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:layout_width="342dp" android:id="@+id/passwordEditText"
android:layout_height="33dp" android:layout_width="289dp"
android:hint="Enter your name" android:layout_height="45dp"
android:inputType="text" android:hint="Enter password"
android:inputType="textPassword"
tools:layout_editor_absoluteX="34d
p" tools:layout_editor_absoluteX="61dp
 Explanation: "
android:hint="Enter your name" : This shows a prompt when the field is empty .
tools:layout_editor_absoluteY="92d
p" /> tools:layout_editor_absoluteY="173d
android:inputType="text" ": This specifies that the
p"input
/> should be plain text (i.e., no
special formatting).

android:inputType="textPassword“ : This will hide the password characters as they are 51


typed.
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.

52
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_cont
ent"

 It is possible to adjust the spacing


android:layout_height="wrap_con
of views:
• Padding: Space between tent" the text and the edges, managed by
each view. android:text="Click Me" />
• Margin: Space around the edges, managed by the parent layout.

53
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

54
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!",
•The onClick(View v)
Toast.LENGTH_SHORT).show();}}
method is called when the }
user clicks the button.
✅ Reusable in multiple
places 55
❌ More code
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 56
❌ Not reusable
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!

57
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

58
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:
CheckBox myCheckBox = findViewById(R.id.myCheckBox);

if (myCheckBox.isChecked()) { We can check if a CheckBox is


// Checkbox is checked checked or not using the
Toast.makeText(this, "Checkbox is checked!", isChecked() method.
Toast.LENGTH_SHORT).show();
} else {
// Checkbox is not checked
Toast.makeText(this, "Checkbox is not checked!",
Toast.LENGTH_SHORT).show(); 59
}
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_conten
t"

android:layout_height="wrap_conte
nt" 60
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.

61
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

62
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
onCreate() When the Activity is created
set 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
opens a notification) . Activity
onPause() When the Activity is partially hidden
is still running, but it is losing
focus
Activity is fully hidden
onStop() When the Activity is no longer visible
(another activity is open)
When the Activity is removed from Activity is shut down and
onDestroy()
memory resources are released
63
When the Activity is restarted after Activity returns from
onRestart()
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)

64
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().

65
ACTIVITY LIFECYCLE

66
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).

67
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
Explicit Intent activity) and 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
Implicit Intent
activity to open, you just say what 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).
68
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 intent = new Intent(MainActivity.this,
is used to start a
SecondActivity.class);
new activity.
startActivity(intent);
});

MainActivity.this: Refers to the


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

69
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);
• key (String) → A unique
intent.putExtra(“isitcom“ , "Hello from
name (identifier) for the
MainActivity!");
data.
startActivity(intent);
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);
70
EXPLICIT INTENT WITH DATA
TRANSFER
📌 Step 2: Receiving Data in SecondActivity
• getStringExtra("key") →
Gets a string value from the
TextView textView = intent.
findViewById(R.id.textView);
// Retrieving the data sent from MainActivity
String message =
getIntent().getStringExtra(“isitcom"); getIntent() → Retrieves the intent
// Displaying the received message in that started the activity.
setText(message)
TextView → Displays the
receivedtextView.setText(message);
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);
71
IMPLICIT INTENT (OPENING
SYSTEM APPS)
Example 1: Open a Web
Intent.ACTION_VIEW → Requests to view a
Page
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.

72
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:
+21693866006"));
startActivity(intent);

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

74
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

75
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.

76
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.

77
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(); 78
Toast.makeText(MainActivity.this,"destroy",Toast.LENGTH_SHORT).show();}
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. 79
SUMMARY FINISH() VS
FINISHAFFINITY()

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

80

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy