目前我有一个湿代码,这是因为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()
}有没有办法让它更好(干燥?)-问题是两个构建器类是不同的。
发布于 2016-08-01 00:42:12
如果您习惯于使用反射,那么不要在构建器中设置小图标,而是在构建通知本身中设置它。您可以在那里检查SDK23,并使用反射调用setSmallIcon (它是一个公共方法,但它是隐藏的。我怀疑它是否会改变),否则在通知中设置图标字段。
发布于 2016-08-01 22:51:59
除了反射,我建议使用两个实现创建您自己的构建器接口:一个用于NotificationCompat.Builder,另一个用于Notification.Builder。你可能在重复"android“,但你不会重复你自己。例如:
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 (或您决定如何调用它)将必须声明您需要的每个公共构建器方法,然后每个实现类将这些方法简单地委托给它们各自的实际构建器实现。
https://stackoverflow.com/questions/38686009
复制相似问题