setSmallIcon(图标:图标)和NotificationCompat

目前我有这样的WET代码造成的事实,NotificationCompat不支持setSmallIcon图标,而不是一个资源ID:

val notification = if (Build.VERSION.SDK_INT < 23) { NotificationCompat.Builder(this) .setLargeIcon(bitmap) .setSmallIcon(R.drawable.ic_launcher) .setContentText(intentDescriber!!.userFacingIntentDescription) .setContentTitle(label) .setContentIntent(contentIntent) .setAutoCancel(true) .build() } else { Notification.Builder(this) .setSmallIcon(Icon.createWithBitmap(bitmap)) .setLargeIcon(bitmap) .setContentText(intentDescriber!!.userFacingIntentDescription) .setContentTitle(label) .setContentIntent(contentIntent) .setAutoCancel(true) .build() } 

有没有办法让这个更好(干?) – 问题是,两个建设者类是不同的..

如果您习惯使用反射,则不要在构建器中设置小图标,而要将其设置在构建的通知中。 您可以在那里查看SDK 23,并使用反射调用setSmallIcon(这是一个公共的方法,但是隐藏的,我怀疑它会改变),否则设置通知中的图标字段。

我建议用两个实现创建自己的构建器接口:一个用于NotificationCompat.Builder ,一个用于Notification.Builder 。 你可能会重复“机器人”,但你不会重复自己 。 例如:

 interface NotificationFacadeBuilder<out T> { /* facade builder method declarations go here */ fun build(): T } class SupportAppNotificationCompatFacadeBuilder(context: Context) : NotificationFacadeBuilder<NotificationCompat> { val builder = NotificationCompat.Builder(context) /* facade builder method implementations go here and delegate to `builder` */ override fun build(): NotificationCompat = TODO() } class AppNotificationFacadeBuilder(context: Context) : NotificationFacadeBuilder<Notification> { val builder = Notification.Builder(context) /* facade builder method implementations go here and delegate to `builder` */ override fun build(): Notification = TODO() } 

NotificationFacadeBuilder (或者你决定调用它的任何东西)将不得不声明你需要的每个常用的构建器方法,然后每个实现的类将简单地委派给它们各自的实际构建器实现。