Skip to main content

ListView et RecyclerView

Bien qu'il existe beaucoup de composants graphique interessant sur Android, nous allons néanmoins illustré les ListView et RecyclerView car ce sont ceux les plus utiliser dans une application professionnelle.

Ces deux composants servent a afficher des liste d'element.

La ListView est plus simple d'utilisation q'un RecyclerView mais moins performant.

ListView

Pour commencer, un exemple d'utilisation avec une liste de chaînes de caractères est le plus simple.

Une liste comporte ces étapes :

  • Ajouter un composant <ListView> avec un identifiant dans le fichier XML
  • Récupérer ce composant dans le fichier Kotlin en utilisant son identifiant
  • Définir un ArrayAdapter, qui permet de déterminer comment afficher chaque élément de la liste
  • Alimenter cette liste à l'aide de l'ArrayAdapter
<?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">

<!-- ListView pour afficher la liste de strings -->
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</LinearLayout>

Customiser la ligne

Pour personnaliser l'affichage de chaque ligne, il faut créer son propre ArrayAdapter personnalisé qui va permettre de surcharger :

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<!-- Un textview dans la cellule -->
<TextView
android:id="@+id/tvMovieTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:padding="10dp"/>

<LinearLayout>

Dans l'Activity l'adapter deviens ceci :

// Adapter personnalisé
val adapter = MovieAdapter(this, movies)