你好 stackoverflow 社区。我正在使用 NotificationCompat 开发通知功能。我希望通知图标在 Android < v11 时变暗,在 Android >=11 时变亮。我遵循了设计指南并创建了图标,但我没有运气自动显示正确的图标。
我找到的所有教程都使用 setIcon(R.drawable.icon_name_here) 设置图标。但是对可绘制资源进行硬编码只允许您设置一个图标。因此,如果它是一个深色图标,它在 Android < v11 中看起来很棒,但在 Android >= v11 中看起来很荒谬。
我尝试在 res/values/styles.xml 中添加以下样式:
<resources>
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
<item name="icon_notification">@drawable/ic_notification_dark</item>
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
这是我的 res/values-v11/styles.xml:
<resources>
<!--
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
<!-- API 11 theme customizations can go here. -->
<item name="icon_notification">@drawable/ic_notification_light</item>
</style>
这是我的 res/values/attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="AppBaseTheme">
<attr name="icon_notification" format="reference" />
</declare-styleable>
</resources>
最后,这是在 NotificationCompat 类中设置图标的地方:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.attr.icon_notification)
.setContentTitle("Notification Title")
.setContentText("notification message")
.setNumber(++num)
.setAutoCancel(true).setOnlyAlertOnce(false)
.setTicker("Ding Dong!").setSound(ringtonePrefUri)
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_VIBRATE);
这就是全部代码。我只想根据 Android 版本设置正确的通知图标。这看起来很简单,但我还没有找到简单明了的解释。请帮忙!
最佳答案
只需使用这样的东西:
int iconRes = (Build.VERSION.SDK_INT < 11) ? R.drawable.icon_dark : R.drawable.icon_light
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(iconRes)
.setContentTitle("Notification Title")
.setContentText("notification message")
.setNumber(++num)
.setAutoCancel(true).setOnlyAlertOnce(false)
.setTicker("Ding Dong!").setSound(ringtonePrefUri)
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_VIBRATE);
关于Android 通知图标 - 黑白切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21647759/