[英]How to dynamically change notification icon color?
我在应用程序中使用了数百个可绘制对象,以在状态栏中带有通知图标的方式动态显示数据。 每个都是由白色文本和透明背景组成的PNG。 我想在某些情况下将白色更改为另一种颜色,但是除了用不同的颜色重新创建数百个相同的图标外,似乎还必须有更好的方法。 有可能用代码做到这一点吗?
我已经找到了更改Drawable
颜色的方法(即: 如何在Android中更改Drawable的颜色? ),但是无法弄清楚如何将其应用于通知图标。 NotifBuilder.setSmallIcon()
调用一个int
,而不是一个Drawable
。
我认为可以将LevelListDrawable与LayerDrawable结合使用:
LevelListDrawable :管理多个备用Drawable的资源,每个Drawable都分配有一个最大值。 使用setLevel(int)设置对象的级别值将使用分配给其max属性的下一个更大或相等的值加载图像。 LevelListDrawable的一个很好的使用示例是电池电量指示器图标,该图标带有不同的图像以指示当前电池电量。
LayerDrawable :管理其他Drawable数组的Drawable。 这些是按数组顺序绘制的,因此索引最大的元素将绘制在顶部。
尝试这个:
您仍然有许多XML可绘制对象,但是比每个图标/颜色组合使用单独的PNG更具动态性。
通知图标不应使用颜色,因为通知图标应该没有颜色。 [1]
彩色图标可能在某些较旧的Android版本上有效,但在较新的平台上则无效。 [2]
[1] http://developer.android.com/design/style/iconography.html#notification
[2] https://developer.android.com/preview/notifications.html#guidelines ,请参阅“使用不同的图标”部分下的注意事项
尝试这个
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
mNotifyBuilder.setContentText(currentText)
.setNumber(++numMessages);
// Because the ID remains unchanged, the existing notification is
// updated.
mNotificationManager.notify(
notifyID,
mNotifyBuilder.build());
...
参见http://developer.android.com/training/notify-user/managing.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.