在一般情况下, 我们利用Notification.Builder 或者NotificationCompat.Builder即可完成常见的需求,谷歌也推荐我们尽量这样做。当系统布局无法满足需求时则通过自定义Layout去实现。
然而谷歌并不推荐开发者自定义状态栏样式,因为各版本以及各rom之间的差异性会导致无法预知的显示问题。点名一下小米4,自定义通知栏会强制加上白色左右padding,如果使用的是深色View,简直丑爆了。
可折叠通知栏样式
依据谷歌规范,自定义Layout在折叠状态下最大高度是64dp,在展开状态下则是256dp。
- 1,定义两个
RemoteView,分别对应折叠状态和展开状态。 - 2,如果不需要定义标题等元素,可调用
Builder.setStyle(),传入一个NotificationCompat.DecoratedMediaCustomViewStyle的标准实例。 - 3,注意控件的颜色或者背景,避免出现黑底黑字或者白底白字等类似问题,推荐使用
TextAppearance_Compat_Notification相关style。
RemoteViews ntfSmall = new RemoteViews(packageName, R.layout.notification_small);
RemoteViews ntfLarge = new RemoteViews(packageName, R.layout.notification_large);
// Apply the layouts to the notification
Notification notification= new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())//可选
.setCustomContentView(ntfSmall)
.setCustomBigContentView(ntfLarge)
.build();
setStyle()可选样式:
- 1.
DecoratedCustomViewStyle:API-24添加,完全自定义模式。向下兼容需依赖appcompat-v7:28.0.0-alpha1及以上版本。分别构建折叠与展开layout - 2.
BigPictureStyle:API-16添加,图像折叠模式,如果设置bigLargeIcon(null)则会使用大图作为缩略图预览; - 3.
BigTextStyle:API-16添加,文字折叠模式,折叠时正常展示普通通知样式,展开后在多出来的区域展示bigText()内容 - 4.
InboxStyle:API-16添加,与BigTextStyle类似,通过addLine(String)方法可以让你在展开状态下多展示最多5行文字! - 5.
MessagingStyle:API-24添加,消息样式,向下兼容需依赖appcompat-v7:28.0.0-alpha1。addMessage()构建消息,在这种样式下ContentTitle和ContentText属性不生效 - 6.
MediaStyle:API-21添加,媒体播放样式,可在构建时添加action实现媒体控制功能














网友评论