我正在尝试向用户显示通知,将计数器显示为图标而不是实际图标。
这就是我想要实现的目标
到目前为止我尝试过的事情
int myCounter = 0;
setSmallIcon(myCounter); // actually the notification won't even display if its not an actual icon
setTickerText(String.valueOf(myCounter)); // This is actualy something different
setLargeIcon(myBitmapWithText); // I also tried generating a bitmap with text, but it won't display since the resource needs to be in the app-package itself
根据我读到的内容,我可以使用
AnimatedDrawable
但创建 50 个不同的可绘制对象来完成该任务确实不合逻辑,除非我别无选择:)
我对此一筹莫展,如何才能达到上述结果?
这个问题在搜索时首先出现,所以我想它在某些时候会对某人派上用场。
fun createTemperatureBitmap(context: Context, temperature: String): Bitmap {
val size = 48
val scale = context.resources.displayMetrics.density
val bitmap = Bitmap.createBitmap((size * scale).toInt(), (size * scale).toInt(), Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.WHITE
textSize = 24 * scale
textAlign = Paint.Align.CENTER
}
val x = bitmap.width / 2f
val y = bitmap.height / 2f - (paint.descent() + paint.ascent()) / 2
canvas.drawText(temperature, x, y, paint)
return bitmap
}
要将其添加为图标,您必须使用
val iconBitmap = createTemperatureBitmap(context, temperature)
和
.setSmallIcon(IconCompat.createWithBitmap(iconBitmap))
*仅适用于 api M 及更高版本