创建自定义通知布局

为了确保您的通知在不同的 Android 版本上都能呈现最佳的视觉效果,您应始终使用标准通知模板构建通知。但是,如果系统模板不能满足您的需求,您可以提供自己的通知布局。

如果您希望在通知中提供更多内容,还可以考虑使用某个展开式通知模板,而不是构建自定义布局。

注意:使用自定义通知布局时,请特别注意确保您的自定义布局适用于不同的设备屏幕方向和分辨率。虽然对于所有界面布局,此建议都适用,但它对通知布局而言尤为重要,因为抽屉式通知栏中的空间非常有限。自定义通知布局的可用高度取决于通知视图。通常情况下,收起后的视图布局的高度上限为 64 dp,展开后的视图布局的高度上限为 256 dp。

为内容区域创建自定义布局

如果您需要自定义布局,可以将 NotificationCompat.DecoratedCustomViewStyle 应用于您的通知。借助此 API,您可以为通常由标题和文本内容占据的内容区域提供自定义布局,同时仍对通知图标、时间戳、子文本和操作按钮使用系统装饰。

该 API 的工作方式与展开式通知模板类似,都是基于基本通知布局,如下所示:

  1. 使用 NotificationCompat.Builder 构建基本通知
  2. 调用 setStyle(),向其传递一个 NotificationCompat.DecoratedCustomViewStyle 实例。
  3. 将自定义布局扩充为 RemoteViews 的实例。
  4. 调用 setCustomContentView() 以设置收起后通知的布局。

    您还可以选择调用 setCustomBigContentView() 为展开后通知设置不同的布局。

例如:

Kotlin

    // 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()
    

Java

    // 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();
    

请注意,通知的背景颜色可能会因设备和版本而异。因此,您应始终在自定义布局中应用支持库样式,例如对文本使用 TextAppearance_Compat_Notification,对标题使用 TextAppearance_Compat_Notification_Title。这些样式会适应颜色的变化,因此不会出现黑色文本采用黑色背景或白色文本采用白色背景的情况。例如:

    <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" />
    

另外,请避免在 RemoteViews 对象上设置背景图片,因为可能会导致文本颜色无法读取。

创建完全自定义的通知布局

如果您不希望使用标准通知图标和标题装饰通知,请按照上述步骤使用 setCustomBigContentView(),但不要调用 setStyle()

如需支持低于 Android 4.1(API 级别 16)的 Android 版本,您还应调用 setContent(),向其传递同一 RemoteViews 对象。

如需获取更多使用通知的示例代码,请参阅 Android 通知示例