Créer une mise en page de notification personnalisée

Pour un rendu optimal de vos notifications sur les différentes versions d'Android, utilisez le modèle de notification standard. Si vous souhaitez ajouter plus de contenu dans votre notification, envisagez d'utiliser l'un des modèles de notification à développer.

Toutefois, si les modèles système ne répondent pas à vos besoins, vous pouvez utiliser votre propre mise en page pour la notification.

Créer une mise en page personnalisée pour la zone de contenu

Si vous avez besoin d'une mise en page personnalisée, vous pouvez appliquer NotificationCompat.DecoratedCustomViewStyle à votre notification. Cette API vous permet de fournir une mise en page personnalisée pour la zone de contenu normalement occupée par le titre et le contenu textuel, tout en utilisant des décorations système pour l'icône de notification, le code temporel, le sous-texte et les boutons d'action.

Cette API fonctionne de la même manière que les modèles de notification extensibles en s'appuyant sur la mise en page des notifications de base comme suit:

  1. Créez une notification de base avec NotificationCompat.Builder.
  2. Appelez setStyle() en lui transmettant une instance de NotificationCompat.DecoratedCustomViewStyle.
  3. Gonflez votre mise en page personnalisée en tant qu'instance de RemoteViews.
  4. Appelez setCustomContentView() pour définir la mise en page de la notification réduite.
  5. Vous pouvez également appeler setCustomBigContentView() pour définir une mise en page différente pour la notification développée.

Préparer les mises en page

Vous avez besoin d'une mise en page small et large. Pour cet exemple, la mise en page small peut se présenter comme suit:

<?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="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/notification_title"
        style="@style/TextAppearance.Compat.Notification.Title"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Small notification, showing only a title" />
</LinearLayout>

La mise en page large peut se présenter comme suit:

<?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="300dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/notification_title"
        style="@style/TextAppearance.Compat.Notification.Title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Large notification, showing a title and a body." />

    <TextView
        android:id="@+id/notification_body"
        style="@style/TextAppearance.Compat.Notification.Line2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="This is the body. The height is manually forced to 300dp." />
</LinearLayout>

Compiler et afficher la notification

Une fois que les mises en page sont prêtes, vous pouvez les utiliser comme indiqué dans l'exemple suivant:

Kotlin

val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

// Get the layouts to use in the custom notification.
val notificationLayout = RemoteViews(packageName, R.layout.notification_small)
val notificationLayoutExpanded = RemoteViews(packageName, R.layout.notification_large)

// Apply the layouts to the notification.
val customNotification = NotificationCompat.Builder(context, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setStyle(NotificationCompat.DecoratedCustomViewStyle())
        .setCustomContentView(notificationLayout)
        .setCustomBigContentView(notificationLayoutExpanded)
        .build()

notificationManager.notify(666, customNotification)

Java

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

// Get the layouts to use in the custom notification
RemoteViews notificationLayout = new RemoteViews(getPackageName(), R.layout.notification_small);
RemoteViews notificationLayoutExpanded = new RemoteViews(getPackageName(), R.layout.notification_large);

// Apply the layouts to the notification.
Notification customNotification = new NotificationCompat.Builder(context, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
        .setCustomContentView(notificationLayout)
        .setCustomBigContentView(notificationLayoutExpanded)
        .build();

notificationManager.notify(666, customNotification);

Sachez que la couleur d'arrière-plan de la notification peut varier selon les appareils et les versions. Appliquez des styles de la bibliothèque Support tels que TextAppearance_Compat_Notification pour le texte et TextAppearance_Compat_Notification_Title pour le titre dans votre mise en page personnalisée, comme illustré dans l'exemple suivant. Ces styles s'adaptent aux variations de couleurs afin que vous n'obteniez pas de texte en noir sur noir ou blanc sur blanc.

<TextView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:text="@string/notification_title"
    android:id="@+id/notification_title"
    style="@style/TextAppearance.Compat.Notification.Title" />

Évitez de définir une image de fond sur votre objet RemoteViews, car votre texte pourrait devenir illisible.

Lorsque vous déclenchez une notification pendant que l'utilisateur utilise une application, le résultat est semblable à la figure 1:

Image montrant une notification réduite
Image 1. Une petite mise en page de notification s'affiche lorsque vous utilisez d'autres applications.

Appuyez sur la flèche de développement pour développer la notification, comme illustré dans la figure 2:

Image montrant une notification développée dans la barre système
Figure 2 : Une grande mise en page s'affiche lorsque vous utilisez d'autres applications.

Une fois le délai de notification expiré, la notification n'est visible que dans la barre système, qui ressemble à la figure 3:

Image montrant une notification réduite dans la barre système
Figure 3 : Affichage de la petite disposition des notifications dans la barre système.

Appuyez sur la flèche de développement pour développer la notification, comme illustré dans la figure 4:

Image montrant une notification développée dans la barre système
Figure 4 : Une mise en page de notification volumineuse s'affiche dans la barre système.

Créer une mise en page de notification entièrement personnalisée

Si vous ne souhaitez pas que votre notification soit accompagnée de l'icône et de l'en-tête de notification standards, suivez les étapes précédentes, mais n'appelez pas setStyle().