Académique Documents
Professionnel Documents
Culture Documents
Java mobile
Chapitre 1
Présentation générale
Présentation .................................................................................................................... 7
I. Développement mobile
Le temps passé sur l'écran de son mobile est de plus en plus important. Selon une étude de TNS
Sofres, les Francais de 16-30 ans sont concentrés sur leur téléphone mobile plus de deux heures
par jour.
Aujourd'hui, il est nécessaire pour chaque entreprise faut d'intégrer le mobile dans sa stratégie
digitale.
Pour intégrer le mobile, il existe trois solutions :
Développer une application native : Une application native est un "logiciel" que l'on
télécharge et que l'on installe sur son smartphone ou sur sa tablette via des plateformes
d'applications (applestore, googleplay, marketplace). Cette application est développée
pour un des systèmes d'exploitation utilisé par les smartphones ou tablettes (Android pour
Google, IOS pour iphone ou Windowsphone pour Microsoft). Elle est développée avec
un language spécifiques aux différents systèmes d'exploitation (type java pour android).
Si vous souhaitez que votre application mobile soit disponible sur les deux principales
plateformes AppleStore et googleplay, vous devrez développer deux applications
distinctes. Il faut une application par système d'exploitation afin que les interfaces et les
usages soient respectés. Ce qui implique un budget conséquent.
Développer une webapplication : Une webapplication (ou webapp), est une application
mobile exécutable via le navigateur internet de votre smartphone. C'est en quelque sorte
"un site internet spécialement conçu pour votre mobile".
Développer une application hybride : Le développement d'une application hybride est
un mix des deux premières solutions: applications natives et webapplications. Elle
combine des éléments HTML5 sous forme de webapplication et des éléments de
l'application native.Le développement d'application hybride repose sur des solutions
comme phonegap/Cordova, qui permettent de créer une application indépendante à partir
de pages webs. Elle permet d'utiliser les fonctions du téléphone et elle est téléchargeables
sur les plateformes apple store, googleplay.
II. Les principaux OS mobiles
• Android (google, …)
• Iphone OS (Apple) sur des téléphones IPhone et sur les tablettes d'Apple
• Windows Mobile (Microsoft) ; système propriétaire
• Symbian (Nokia) ; récemment passé en open source
• BlackBerry OS. Présent sur tous les téléphones de la marque RIM (Research In
Motion) ;
• Palm Web OS (successeur de Palm Os)
•LiMo (Linux Mobile),système ouvert basé sur Linux
(http://www.tizenassociation.org/en/)
• MeeGo, Intel et Nokia (https://meego.com/)
• Bada, Samsung (http://www.bada.com/whatisbada/index.html
III. Présentation Android
Android doit son nom à la startup éponyme spécialisée dans le développement d’applications
mobiles rachetée par Google en août 2005, nom venant lui-même d'« androïde » qui désigne un
robot construit à l'image d'un être humain.
Lancé en juin 2007 à la suite du rachat par Google en 2005 de la startup du même nom, le
système avait d'abord été conçu pour les smartphones et tablettes tactiles, puis s'est diversifié
dans les objets connectés et ordinateurs comme :
V. Google play
Google Play (Play Store), est une boutique en ligne créée par Google (le 6 mars 2012) par fusion
des services Android Market et d'autres services Google (location de films, achat de musique,
etc.). Elle permet de télécharger et d'installer de nouvelles applications ("apps") dans le
smartphone.
Android market est "né" le 22 octobre 2008 ".
Au 30 octobre 2012, Google Play est fort de 700 000 applications ce qui le met à égalité avec
iOS" : voir historique à http://fr.wikipedia.org/wiki/Android_Market.
Les développeurs d'applications payantes reçoivent 70 % du prix du logiciel, 30 % allant à
Google Chaque nouveau développeur paie $25 comme frais de dossier (une seule fois).
Applications - Le projet Open Source Android contient plusieurs applications par défaut
comme le navigateur, l'appareil photo, la galerie, la musique, le téléphone et plus encore ;
Application Framework - Une API qui permet aux applications Android d'interagir avec
le système Android ;
Libraries and runtime - Les bibliothèques pour de nombreuses fonctions communes
(par exemple : le rendu graphique, le stockage de données, la navigation sur le Web, etc.)
de l'Application Framework et du moteur Dalvik, ainsi que le noyau de bibliothèques
Java pour exécuter des applications Android ;
Linux kernel - La couche de communication avec le matériel sous-jacent.
X. Android Studio
1. Présentation
Android Studio est un environnement de développement pour développer des applications
Android. Il est basé sur IntelliJ IDEA.
Avant Android Studio, de 2009 à 2014, Google propose comme environnement de
développement officiel une distribution spécifique de l'environnement Eclipse, contenant
notamment le SDK d'Android.
2. Le fichier manifest.xml
Nomme le paquetage Java de l'application. Ce dernier sert d'identificateur unique de
l'application.
Déclare les composants applicatifs (activities, services, broadcast receivers, content providers) de
l'application et leurs filtres si nécessaire (à quels intents ils réagissent)
Déclare les permissions que l'application doit avoir pour fonctionner (droit de passer des appels,
droit d'accéder à Internet, droit d'accéder au GPS...)
Chapitre 2
II. TextView................................................................................................................ 11
Toast.makeText(this,"Premier Message",Toast.LENGTH_SHORT).show();
package com.example.dell.exemple01_toast;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this,"Premier Message",Toast.LENGTH_SHORT).show();
}
}
II. TextView
Un TextView peut être défini comme un titre ou bien un paragraphe se situant à l'intérieur d'une
page d'une application mobile Android.
Un TexTview est utilisé pour afficher sur une page une information à un utilisateur. Cela vous
permet de mettre de plus un titre à des images ou des descriptions.
Les principaux attributs de ce composant sont :
Attribut Description
android:id Identifiant du contrôle. Il doit être unique dans
le l’activité.
android:text Le texte qui sera affiche dans le contrôle.
android:textcolor La couleur du texte du contrôle
android:textSize La taille du texte
android:textStyle Cet attribut peut contenir les valeurs suivantes :
0 : normal
1 : Bold
2 : Italic
Android :textalign Alignement du texte : center ; TextStart ;
TextEnd
TextView t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView)findViewById(R.id.t1);
t.setText("TDI - Module de développement");
t.setTextColor(Color.GREEN);
t.setBackgroundColor(Color.GRAY);
…
}
}
Exercice d’application
1. Créer un nouveau projet sous android studio.
2. Dans le code XML de l’activité, modifier le type de layout en
LinearLayout.
3. Ajouter l’attribut Orientation = Verticale aux attributs de
LinearLayout.
4. Construire l’interface suivante :
5. Tester votre application.
6. Supprimer les attributs text et textColor des textView de votre
fichier XML et ajouter les à partir du code Java.
III. EditText
Permet de spécifier des zones de saisis dans vos activités.
Les principaux attributs de composants sont :
L’attribut Description
android:id Identifiant du contrôle. Il doit être unique dans le
l’activité.
android:text Le texte qui sera affiche dans le contrôle.
android:textcolor La couleur du texte du contrôle
android:textSize La taille du texte
EditText t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (EditText) findViewById(R.id.t1);
}
}
Exercice d’application
- Créer une application sous android studio.
- Créer l’IHM suivant :
IV. Button
Un button qui peut être pressé ou cliqué par l'utilisateur d'effectuer une action.
Pour récupérer le button dans le code java :
Button t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (Button) findViewById(R.id.b1);
}
t = (Button) findViewById(R.id.b1);
t.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
2ème méthode
Button t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (Button) findViewById(R.id.b1);
t.setOnClickListener(this);
@Override
}
}
}
Exercices d’application
Exercice 1
- Créer une application sous android studio.
- Créer l’interface suivante :
- Ajouter un événement click au button qui permet d’afficher
dans une annonce Toast le mail saisi.
Exercice 2
- Créer une application sous android studio.
- Créer l’interface suivante :
- Ajouter un événement au button, qui permet d’afficher
le message TVA le prix TTC dans un message Toast, sous la
forme PRIX TTC = 12.45 DH.
Le fichier MainActivity.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TVA : "/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tva"
android:inputType="numberDecimal"
android:background="#41ef3e"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculer le TTC"
android:id="@+id/b1"/>
</LinearLayout>
Le fichier MainActivity.java
EditText t1,t2 ;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (EditText) findViewById(R.id.pht);
t2 = (EditText) findViewById(R.id.tva);
b = (Button) findViewById(R.id.b1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double pht = Double.parseDouble(t1.getText().toString());
double tva = Double.parseDouble(t2.getText().toString());
double ttc = pht * (1+tva/100);
Toast.makeText(getApplication(), "PTTC : " + ttc, Toast.LENGTH_SHORT).show();
t1.setText("");
t2.setText("");
}
});
}
}
Exercice 3
- Créer une application sous android studio
- Créer l’interface suivant :
- Ajouter le code du button qui permet d’afficher
Connection OK si le login saisi est « toto » et le mot
de passe « toto ». Sinon le message « Connection KO »
sera affiché
Le fichier MainActivity.xml
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000"
tools:context="com.example.formateur.ex01_tdi202.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/login"
android:background="#ebf1ea"
android:layout_margin="10dp"
android:hint="Tapez votre login .."/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/pass"
android:inputType="numberPassword"
android:background="#ebf1ea"
android:layout_margin="10dp"
android:hint="Tapez votre password .."/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connecter"
android:id="@+id/b1"
android:layout_margin="10dp"/>
</LinearLayout>
Le fichier MainActivity.java
EditText t1,t2 ;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (EditText) findViewById(R.id.login);
t2 = (EditText) findViewById(R.id.pass);
b = (Button) findViewById(R.id.b1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(t1.getText().toString().equals("toto") && t2.getText().toString().equals("toto"))
Toast.makeText(getApplication(), "Connexion Reussie", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplication(), "Echec Conenxnion", Toast.LENGTH_SHORT).show();
}
});
}
}
Exercice 4
- En se basant sur l’ancien projet de l’exercice 3.
- Ajouter à votre projet la classe Utilisateur qui contient les éléments suivant :
o Les attributs : login et password
o Les accesseurs
- Dans la classe java de l’activité remplir une liste d’utilisateur.
- Modifier l’événement du button pour afficher Connection OK si le login et le mot de
passe existe dans la liste sinon le message « Connection KO » sera affiché.
Le fichier .xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000"
tools:context="com.example.formateur.ex01_tdi202.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/login"
android:background="#ebf1ea"
android:layout_margin="10dp"
android:hint="Tapez votre login .."/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/pass"
android:inputType="numberPassword"
android:background="#ebf1ea"
android:layout_margin="10dp"
android:hint="Tapez votre password .."/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connecter"
android:id="@+id/b1"
android:layout_margin="10dp"/>
</LinearLayout>
Le fichier .java
EditText t1,t2 ;
Button b;
List<Utilisateur> users = new ArrayList<Utilisateur>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (EditText) findViewById(R.id.login);
t2 = (EditText) findViewById(R.id.pass);
b = (Button) findViewById(R.id.b1);
users.add(new Utilisateur("login1","123456"));
users.add(new Utilisateur("login2","123456"));
users.add(new Utilisateur("login3","123456"));
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean trouve = false;
if(trouve)
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Nombre 2 :"
android:textColor="#faf2f2"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/zone2"
android:background="#9ff9a3"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Somme"
android:id="@+id/b1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Soustraction"
android:id="@+id/b2"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Produit"
android:id="@+id/b3"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Division"
android:id="@+id/b4"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Resultat :"
android:textColor="#faf2f2"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/zone3"
android:background="#9ff9a3"/>
</LinearLayout>
Fichier .java
EditText t1,t2,t3 ;
Button b1,b2,b3,b4;
List<Utilisateur> users = new ArrayList<Utilisateur>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (EditText) findViewById(R.id.zone1);
t2 = (EditText) findViewById(R.id.zone2);
t3 = (EditText) findViewById(R.id.zone3);
b1 = (Button) findViewById(R.id.b1);
b2 = (Button) findViewById(R.id.b2);
b3 = (Button) findViewById(R.id.b3);
b4 = (Button) findViewById(R.id.b4);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
@Override
public void onClick(View v) {
double a = Double.parseDouble(t1.getText().toString());
double b = Double.parseDouble(t2.getText().toString());
double c=0;
switch (v.getId()) {
case R.id.b1:
c = a + b;
break;
case R.id.b2:
c = a - b;
break;
case R.id.b3:
c = a * b;
break;
case R.id.b4:
if (b == 0)
Toast.makeText(getApplicationContext(), "Operation Invalid",
Toast.LENGTH_LONG).show();
else
c = a / b;
break;
}
t3.setText(String.valueOf(c));
}
Chapitre 2
I. LinearLayout
Ce Layout se charge de mettre les vues sur une même ligne, selon une certaine orientation
(Verticale ou horizontale). L'attribut pour préciser cette orientation est android:orientation. On
peut lui donner deux valeurs :
Vertical : pour que les composants soient placés de haut en bas (en colonne) ;
Horizontal : pour que les composants soient placés de gauche à droite (en ligne).
<LinearLayout
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:id="@+id/btn01"
android:text="Bouton 01"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn02"
android:text="Bouton 02"/>
</LinearLayout>
Exemple 2 : Positionner les deux boutons d’une façon verticale :
Le fichier activity_main.xml avec le résultat sont affichés ci-après :
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn01"
android:text="Bouton 01"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn02"
android:text="Bouton 02"/>
</LinearLayout>
Exemple 3 : Utilisation des layouts imbriqués :
Le fichier activity_main.xml avec le résultat sont affichés ci-après :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.dell.myapplicationgravite.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button01" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button02" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button03" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button04" />
</LinearLayout>
</LinearLayout>
Exemple 2 :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dell.myapplicationgravite.MainActivity"
android:gravity="center"
android:background="#8385f7">
<LinearLayout
android:layout_width="300dp"
android:layout_height="100dp"
android:orientation="vertical"
android:background="#c1f5c1"
android:gravity="center"
>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Saisir votre messsage ..."
android:background="#78ecd7"/>
<Button
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Envoyer"
android:layout_gravity="center"
android:id="@+id/button"
android:layout_margin="5dp"
android:background="#e90dd3"/>
</LinearLayout>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button01"
android:layout_weight="1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button02"
android:layout_weight="1"
/>
</LinearLayout>
Si l’on met une valeur 1 au premier et 2 au second, le deuxième prendra deux fois plus
d’espace libre que le premier (Par défaut la valeur du poids est de 0).
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button01"
android:layout_weight="1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button02"
android:layout_weight="2"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nombre 1 :"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000"
android:layout_weight="1"
android:layout_marginRight="15dp"/>
</LinearLayout>
<!-- sgdfgdfg -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nombre 1 :"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000"
android:layout_weight="2"
android:layout_marginRight="15dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="10dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="*"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="/"
android:layout_weight="1"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resultat :"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000"
android:layout_weight="2"
android:layout_marginRight="15dp"/>
</LinearLayout>
</LinearLayout>
2.
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#10e71e"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Prénom : "/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#10e71e"/>
</LinearLayout>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Homme"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Femme"/>
</LinearLayout>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="date"
android:background="#10e71e"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Liste des diplomes : "
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:layout_weight="2"
android:layout_margin="10dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RAZ"
android:layout_weight="1"
android:layout_margin="10dp"/>
</LinearLayout>
</LinearLayout>
3.
Exercice 2 :
Développer une calculatrice :
Solution de l’exercice 2 :
Le ficher .java
ed=(EditText) findViewById(R.id.zone);
}
break;
}
}
}
Le fichier .xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#b0fbd5"
tools:context="com.example.formateur.calculatriceapp.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="50dp"
android:hint="0"
android:gravity="right"
android:background="#faf7f7"
android:layout_weight="1"
android:id="@+id/zone"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C"
android:textSize="30dp"
android:id="@+id/btnC"
android:layout_weight="1"
android:background="#4f13f5"
android:textColor="#fbf8f8"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="%"
android:textSize="30dp"
android:id="@+id/btnMod"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="/"
android:textSize="30dp"
android:id="@+id/btnDiv"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:textSize="30dp"
android:id="@+id/btn1"
android:layout_weight="1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:textSize="30dp"
android:id="@+id/btn2"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:textSize="30dp"
android:id="@+id/btn3"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:textSize="30dp"
android:id="@+id/btnPlus"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4"
android:textSize="30dp"
android:id="@+id/btn4"
android:layout_weight="1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5"
android:textSize="30dp"
android:id="@+id/btn5"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="6"
android:textSize="30dp"
android:id="@+id/btn6"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:textSize="30dp"
android:id="@+id/btnMoins"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="7"
android:textSize="30dp"
android:id="@+id/btn7"
android:layout_weight="1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8"
android:textSize="30dp"
android:id="@+id/btn8"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9"
android:textSize="30dp"
android:id="@+id/btn9"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="*"
android:textSize="30dp"
android:id="@+id/btnProd"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=","
android:textSize="30dp"
android:id="@+id/btnVir"
android:layout_weight="1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="30dp"
android:id="@+id/btn0"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+/-"
android:textSize="30dp"
android:id="@+id/btnPM"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="="
android:textSize="30dp"
android:id="@+id/btnEgale"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
Chapitre 2
I. RadioButton
On regroupe les RadioButton dans un RadioGroup.
Exemple :
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Homme" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Femme"
</RadioGroup>
rd1.setChecked(true);
rd2.setChecked(false);
if(rd1.isChecked())
Toast.makeText(this,"radio 1 coché",Toast.LENGTH_LONG).show();
if(rd2.isChecked())
Toast.makeText(this,"radio 2 coché",Toast.LENGTH_LONG).show();
Pour Créer un événement si le radioButton est coché :
rd1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(getApplicationContext(),"radio 1 coché",Toast.LENGTH_LONG).show();
}
});
II. ImageView
Cette vue permet d’afficher des images.
Exemple :
<ImageView
android:layout_width="368dp"
android:layout_height="495dp"
android:src="@drawable/i1"
android:id="@+id/img"/>
Exercice 2 :
Exercice 3 :
Solution :
Le fichier xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nom : "/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/nom"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Prénom : "/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/prenom"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sexe : "/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Homme"
android:id="@+id/r1"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Homme"
android:id="@+id/r2"/>
</RadioGroup>
</LinearLayout>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/img"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="<<"
android:id="@+id/b1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="<"
android:id="@+id/b2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=">"
android:id="@+id/b3"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=">>"
android:id="@+id/b4"/>
</LinearLayout>
</LinearLayout>
Le fichier java.
int pos=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
st.add(new Stagiaire("TAN","THOMAS","HOMME",R.drawable.i1));
st.add(new Stagiaire("BABI","ISA","FEMME",R.drawable.i2));
st.add(new Stagiaire("HAKAM","MARINE","FEMME",R.drawable.i3));
st.add(new Stagiaire("DEPEL","NICOLAS","HOMME",R.drawable.i4));
r1 = (RadioButton) findViewById(R.id.r1);
r2 = (RadioButton) findViewById(R.id.r2);
b1 = (Button) findViewById(R.id.b1);
b2 = (Button) findViewById(R.id.b2);
b3 = (Button) findViewById(R.id.b3);
b4 = (Button) findViewById(R.id.b4);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
pos=0;
remplissage();
}
nom.setText(st.get(pos).getNom());
prenom.setText(st.get(pos).getPrenom());
if(st.get(pos).getSexe().equals("HOMME"))
r1.setChecked(true);
if(st.get(pos).getSexe().equals("FEMME"))
r2.setChecked(true);
img.setImageResource(st.get(pos).getImage());
img.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN)
x1=event.getX();
if(event.getAction()==MotionEvent.ACTION_UP) {
x2 = event.getX();
if (pos == st.size())
pos = 0;
if (pos == -1)
pos = st.size()-1;
remplissage();
}
return true;
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.b1 :
pos=0;
break;
case R.id.b2 :
pos--;
if(pos==-1)
pos=st.size()-1;
break;
case R.id.b3 :
pos++;
if(pos==st.size())
pos=0;
break;
case R.id.b4 :
pos = st.size()-1;
break;
}
remplissage();
}
}
Chapitre 3
Les INTENTS
I. Définition
Les Intents sont des messages qui permettent aux composants d'une application de demander
des fonctionnalités à d’autres composants Android.
Les Intents vous permettent d'interagir avec vos propres composants ou des composants d'autres
applications. Par exemple, une activité peut démarrer une autre activité pour prendre une photo.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ouvrir l'activité 2"
android:id="@+id/b"/>
</LinearLayout>
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
2. Avec transmission des données
Voici un exemple d’ouverture d’activité avec transmission des données :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:gravity="center"
android:orientation="vertical"
tools:context="com.example.dell.ouvertureactivities.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Valeur 1 : "
android:textSize="20dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/e1"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Valeur 2 : "
android:textSize="20dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/e2"
/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ouvrir l'activité 2"
android:id="@+id/b"/>
</LinearLayout>
Button b;
EditText e1,e2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button) findViewById(R.id.b);
e1=(EditText) findViewById(R.id.e1);
e2=(EditText) findViewById(R.id.e2);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),Main2Activity.class);
i.putExtra("val1",e1.getText());
i.putExtra("val2",e2.getText());
startActivity(i);
}
});
}
}
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tv = (TextView) findViewById(R.id.tv);
Exercice d’application
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/t1"
android:hint="Votre N° de tél ...."
android:inputType="phone"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Appeler"
android:id="@+id/b1"/>
</LinearLayout>
Dans le fichier JAVA :
EditText e;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e = (EditText) findViewById(R.id.t1);
b = (Button) findViewById(R.id.b1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String tel = e.getText().toString();// Votre numéro de téléphone
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + tel));
startActivity(callIntent);
}
});
}
}
2. Camera
Voici un exemple d’utilisation de la caméra dans une application android.
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/b1"
android:text="Prendre photo"
android:layout_gravity="center"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/img"/>
</LinearLayout>
Dans le fichier JAVA :
ImageView img;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i,0);
}
});
}
@Override
protected void onActivityReult(int requestCode, int resultCode, Intent data){
Bitmap bit = (Bitmap) data.getExtras().get("data");
img.setImageBitmap(bit);
}
}
Chapitre 4
Les LISTVIEW
I. Introduction
Sous Android, le composant principal pour afficher et gérer une liste de données est le
composant ListView.
Par défaut ce composant affiche une liste de chaines de caractères. Selon les besoins, il peut être
nécessaire d'afficher plus d'informations sur chaque ligne de la liste, ou même de venir effectuer
des opérations particulières suite à des actions sur les lignes.
1. ArrayAdapter et ListView
Il permet d’afficher les données d’un ArrayList, mais il est limité à une seule chaîne par item.
Exemple :
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/liste">
</ListView>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:id="@+id/t1"
/>
</LinearLayout>
Le fichier JAVA :
ListView liste;
String[] chaines;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
liste = (ListView) findViewById(R.id.liste);
final String[] chaines = {"Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi"};
ArrayAdapter <String> ad =new ArrayAdapter<String>(this,R.layout.ligne_item,R.id.t1,chaines);
liste.setAdapter(ad);
liste.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), chaines[i], Toast.LENGTH_SHORT).show();
}
});
}
}
2. Exercice d’application
1. Créer une nouvelle application sous Android studio.
2. Créer une activité qui permet d’afficher la liste des filières
de l’ENSA.
3. Ajouter un événement qui va permettre à chaque clique sur
une filière d’afficher plus d’informations sur cette filière :
a. Description
b. Nombre d’heures
c. Type de formation
d. Formateur
L’adaptateur répond à la question que pose le ListView : « que dois-je afficher à tel endroit dans
la liste ?». Il va chercher les données et instancie le layout d’item avec les valeurs.
La génération de vues pour afficher les items repose sur un mécanisme appelé LayoutInflater
qui fabrique des vues Android à partir d’un layout XML :
Exemple :
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
}
ArrayList<Pays> pays;
Context c;
this.pays = pays;
this.c = context;
}
@Override
public int getCount() {
return pays.size();
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null) {
convertView = LayoutInflater.from(c).inflate(R.layout.item_row, parent, false);
v.image = (ImageView) convertView.findViewById(R.id.img);
v.texte = (TextView) convertView.findViewById(R.id.NameCountry);
}
else
{
v =(ViewHolder) convertView.getTag();
}
v.image.setImageResource(pays.get(position).getImage());
v.texte.setText(pays.get(position).getNom());
convertView.setTag(v);
return convertView;
}
{
ImageView image;
TextView texte;
}
}
3. Dans le main_activity.java :
public class MainActivity extends AppCompatActivity {
ListView listv;
ArrayList<Pays> pays = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pays.add(new Pays(R.drawable.algeria64,"Algerie"));
pays.add(new Pays(R.drawable.argentina64,"Argentina"));
pays.add(new Pays(R.drawable.brazil64,"Brazil"));
pays.add(new Pays(R.drawable.ghana64,"Ghana"));
pays.add(new Pays(R.drawable.spain64,"Spain"));
listv.setAdapter(p);
listv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,DetailActivity.class);
intent.putExtra("countryname",pays.get(position).getNom());
intent.putExtra("countryflag",pays.get(position).getImage());
startActivity(intent);
}
});
}
}
4. Le fichier main_activity.XML :
<LinearLayout 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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.dell.exemple_flagcountries.MainActivity">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="?attr/actionBarTheme"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:id="@+id/toolbar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
app:theme="@style/Base.ThemeOverlay.AppCompat.Light"
app:title="List of countries" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listv"
>
</ListView>
</LinearLayout>
5. Le fichier item_row.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:src="@drawable/chile64"
android:id="@+id/img"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Name of the country"
android:id="@+id/NameCountry"/>
</LinearLayout>
</LinearLayout>
Exercice d’application
1. Créer une application sous android studio.
2. Ajouter la classe contact qui contient les informations suivantes :
a. Image (int)
b. Nom
c. Prénom
d. Email
e. Fax
f. Tel fixe
g. Tel portable.
3. Créer une activité qui va permettre d’afficher une liste des contacts. Les informations à
afficher dans chaque item sont :
a. Image
b. Nom
c. Prénom
La clique sur un item permet d’ouvrir une autre activité pour afficher tous les informations.
Chapitre 5
SQLLite est le SGBD le plus distribué au monde, grâce à son utilisation dans de nombreux
logiciels grand public comme Firefox, Skype et dans certains produits d'Apple, d'Adobe et de
McAfee et dans les bibliothèques standards de nombreux langages comme PHP ou Python.
Une base de données sous Android nécessite peu de mémoire lors de l'exécution (env. 250 ko),
ce qui en fait un bon candidat pour être intégré dans d'autres environnements d'exécution.
SQLite est intégrée dans chaque appareil Android. L'utilisation d'une base de données SQLite
sous Android ne nécessite pas de configuration ou d'administration de la base de données.
Vous devez uniquement définir les instructions SQL pour créer et mettre à jour la base de
données. Ensuite, celleci est gérée automatiquement pour vous, par la plate-forme Android.
Si votre application crée une base de données, celle-ci est par défaut enregistrée dans le
répertoire
DATA /data/ APP_NAME/databases/FILENAME.
Pour créer et mettre à jour une base de données dans votre application Android, vous créez une
classe qui hérite de SQLiteOpenHelper. Dans le constructeur de votre sous-classe, vous appelez
la méthode super( ) de SQLiteOpenHelper, en précisant le nom de la base de données et sa
version actuelle.
Dans cette classe, vous devez redéfinir les méthodes suivantes pour créer et mettre à jour votre
base de données :
onCreate() : est appelée pour accéder à une base de données qui n'est pas encore créée.
onUpgrade() : Cette méthode vous permet de mettre à jour un schéma de base de
données existant ou de supprimer la base de données existante et la recréer par la
méthode onCreate().
Exemple :
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_NAME + " ("+COL_1 + " INTEGER
PRIMARY KEY AUTOINCREMENT, "+ COL_2 + " TEXT, "+COL_3 + " TEXT, "+COL_4+"
INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
}
Dans le fichier MainActivity.java :
MyDataBase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Pour chaque table, il faut créer une classe qui contient les mêmes champs que la table :
public Student(){
}
public Student(int id, String nom, String prenom, int note) {
this.id = id;
this.nom = nom;
this.prenom = prenom;
this.note = note;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public int getNote() {
return note;
}
public void setNote(int note) {
this.note = note;
}
}
tools:context="mobile.tetouan.ofppt.ismo.exemple1sqlite.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nom : "/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/t_nom"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Prénom : "/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/t_prenom"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Note : "/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="numberDecimal"
android:id="@+id/t_note"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/btn_save"/>
</LinearLayout>
</LinearLayout>
MyDataBase db;
EditText t1,t2,t3;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new MyDataBase(this);
t1 = (EditText) findViewById(R.id.t_nom);
t2 = (EditText) findViewById(R.id.t_prenom);
t3 = (EditText) findViewById(R.id.t_note);
b1 = (Button) findViewById(R.id.btn_save);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Student s = new Student();
s.setNom(t1.getText().toString());
s.setPrenom(t2.getText().toString());
s.setNote(Integer.parseInt(t3.getText().toString()));
long r=MyDataBase.insertStudent(db.getWritableDatabase(),s);
if(r!=-1){
Toast.makeText(getApplicationContext(),"Insertion
Reussie",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"Insertion
Echoue",Toast.LENGTH_LONG).show();
}
}
});
}
}
Il faut ajouter la méthode insertStudent dans la classe MyDataBase comme suit :
return result;
}
tools:context="mobile.tetouan.ofppt.ismo.exemple1sqlite.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list">
</ListView>
</LinearLayout>
Le fichier MainActivity.java :
MyDataBase db;
ListView lst;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new MyDataBase(this);
int i=0;
for(Student s:sts) {
noms[i] = s.getNom();
i++;
}
while(cur.moveToNext()){
Student s = new Student();
s.setId(cur.getInt(0));
s.setNom(cur.getString(1));
s.setPrenom(cur.getString(2));
s.setNote(cur.getInt(3));
stds.add(s);
}
return stds;
}
db.close();
return result;
}
return result;
}
Chapitre 6
LES RESSOURCES
1. Introduction ........................................................................................................ 71
I. Les ressources
1. Introduction
Nous allons désormais parler des ressources. Les ressources sont des fichiers qui contiennent des
informations qui ne sont :
Pas en Java (ce n'est donc pas du code).
Pas dynamique (le contenu d'une ressource restera inchangé entre le début de l'exécution
de votre application et la fin de l'exécution).
L'avantage des ressources, c'est qu'elles nous permettent de nous adapter facilement à toutes ces
situations différentes.
<string-array name="exemple2">
<item>TDI</item>
<item>TRI</item>
<item>INFO</item>
<item>TMSIR</item>
<item>CRJJ</item>
<item>BCMOS</item>
</string-array>
</resources>
<TextView
android:id="@+id/id1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/exemple1"
/>
String[] s = getResources().getStringArray(R.array.exemple1);
3. Les couleurs
Les couleurs sont enregistrés dans le fichier colors.xml.
Exemple de déclaration :
<resources>
<color name="opaque_red">#f00</color>
<color name="translucent_red">#80ff0000</color>
</resources>
4. Les styles
Un style est une collection de propriétés qui spécifient le design d'une vue, d'un élément ou d'une
application. Il peut spécifier différentes propriétés :
Margin ;
Hauteur ;
Largeur ;
Couleur du texte ;
Taille du texte ;
etc.
Un style se définit dans un fichier ressource XML séparé du fichier XML de votre vue. Ce
fichier se nomme en général styles.xml et se situe dans le dossier values.
<style name="style1">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">match_parent</item>
<item name="android:textSize">30dp</item>
<item name="android:textColor">@color/opaque_red</item>
</style>
<TextView
style="@style/style1"
android:text="@string/hello" />
Exemple de déclaration :
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
</shape>
Exemple d’utilisation :
<Button
android:id="@+id/aj_b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/aj_remove"
android:background="@drawable/ex1"/>
<selector xmlns:android="http://schemas.android.com/apk/res/android">