【Interface&navigation】创建一个自定义通知(43)


为确保您的通知在不同版本的Android中看起来最佳,您应始终使用标准通知模板来构建通知。但是,如果系统模板不能满足您的需求,您可以为通知提供自己的布局。

如果要在通知中提供更多内容,还应考虑使用其中一个可扩展通知模板,而不是构建自定义布局。

警告:使用自定义通知布局时,请特别注意确保自定义布局使用不同的设备方向和分辨率。虽然此建议适用于所有UI布局,但对于通知尤为重要,因为通知抽屉中的空间非常有限。自定义通知布局的可用高度取决于通知视图。通常,折叠视图布局限制为64 dp,扩展视图布局限制为256 dp。

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


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

通过构建基本通知布局,此API与可扩展通知模板的工作方式类似,如下所示:

建立一个基本的通知 用NotificationCompat.Builder。
调用setStyle(),传递它的一个实例NotificationCompat.DecoratedMediaCustomViewStyle。
将您的自定义布局充气为RemoteViews。
调用 setCustomContentView()以设置折叠通知的布局。

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

注意:如果您要为媒体播放控件创建自定义通知,请遵循相同的建议,但请使用 NotificationCompat.DecoratedMediaCustomViewStyle 该类。

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

扫描二维码关注公众号,回复: 2743870 查看本文章

警告:建议不要使用未修改的通知,因为您的通知与其他通知不匹配,并且可能会在将不同样式应用于通知区域的不同设备上导致严重的布局兼容性问题。

要支持早于Android 4.1(API级别16)的Android版本,您还应该调用setContent()它,并将其传递给相同的RemoteViews对象。

联系我

QQ:94297366
微信打赏:https://pan.baidu.com/s/1dSBXk3eFZu3mAMkw3xu9KQ

公众号推荐:

【Interface&navigation】创建一个自定义通知(43)

猜你喜欢

转载自blog.51cto.com/4789781/2158894