【问题标题】:setSmallIcon(icon:Icon) and NotificationCompatsetSmallIcon(icon:Icon) 和 NotificationCompat
【发布时间】:2016-07-31 16:19:08
【问题描述】:

目前我有这个 WET 代码,因为 NotificationCompat 不支持图标而不是资源 ID 的 setSmallIcon:

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

有没有办法让它变得更好(DRY?) - 问题是两个构建器类是不同的..

【问题讨论】:

  • SDK 23 引入 Icon 类,compat 无法支持。
  • 但它可能需要一个位图,并且在 23 impl 中它可以使用 Icon 并为这个 SDK 级别及更高级别包装位图
  • 您可以随时制作自己的构建器类...

标签: android notifications kotlin


【解决方案1】:

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

【讨论】:

  • 通知没有公共 setSmallIcon - 只有构建器有
  • 对不起,文档骗了我。它有一个 getSmallIcon 但没有一个 setSmallIcon。 setSmallIcon 的链接指向生成器。
  • 不用担心 - 但可能会删除答案以清理问题
  • 反射不会使这个工作代码更好恕我直言;-)
【解决方案2】:

我建议使用两种实现创建您自己的构建器接口:一种用于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(或任何您决定调用它的名称)必须声明您需要的每个公共构建器方法,然后每个实现类将简单地将这些委托给它们各自的实际构建器实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多