Android通知图标 - 切换黑白

时间:2014-02-08 15:21:19

标签: android notifications icons compatibility

Hello stackoverflow社区。我正在使用NotificationCompat处理通知功能。我想Android的通知图标是黑暗的<适用于Android的v11和light> = 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版本设置正确的通知图标。这似乎很简单,但我没有找到一个简单明了的解释。请帮忙!

1 个答案:

答案 0 :(得分:1)

只需使用以下内容:

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);