【问题标题】:How to change Notification action text color in Android N?如何在 Android N 中更改通知操作文本颜色?
【发布时间】:2017-04-25 16:36:47
【问题描述】:

是否可以更改'FIRE'/'AMBULANCE'/'POLICE'的文字颜色?

或者像在旧版本的 Android 中那样为它们添加图标?

【问题讨论】:

标签: android


【解决方案1】:
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setColor(ContextCompat.getColor(context, R.color.colorPrimary));

NotificationCompat.Builder.setColor 方法用于为通知设置强调色,这也将应用于操作按钮的文本。

【讨论】:

  • 它也会改变通知的smallIcon颜色。
【解决方案2】:

要更改操作文本颜色,请使用:

HtmlCompat.fromHtml("<font color=\"" + ContextCompat.getColor(context, R.color.custom_color) + "\">" + context.getString(R.string.fire) + "</font>", HtmlCompat.FROM_HTML_MODE_LEGACY)

作为动作标题CharSequence,如:

Notification notification = new NotificationCompat.Builder(context, channelId)
        ...
        .addAction(new NotificationCompat.Action.Builder(
                            R.drawable.ic_fire,
                            HtmlCompat.fromHtml("<font color=\"" + ContextCompat.getColor(context, R.color.custom_color) + "\">" + context.getString(R.string.fire) + "</font>", HtmlCompat.FROM_HTML_MODE_LEGACY),
                            actionPendingIntent))
                    .build())
        .build();

【讨论】:

  • 很奇怪,这是这样做的方式。在 Android 9 上,如果我设置字体颜色,它会更改按钮的 backgroundColor。
  • 奇怪且无证 恐怕,我猜是根据参数类型CharSequense判断使用可跨字符串。
  • 在 Android 8 和 Android 10 上试用过,它的行为应有尽有
【解决方案3】:

要更改动作的文本颜色并在其左侧放置一个图标,请使用以下示例。

NotificationCompat.Builder(context).setColor(ContextCompat.getColor(context, R.color.yourColorResourceHere))
.addAction(android.R.drawable.ic_menu_close_clear_cancel, "Fire", myPendingIntent);

【讨论】:

  • 图标未显示。我猜它们只出现在较旧的 android 版本中。
  • addAction 按钮文本颜色在 android 10 中更改。
【解决方案4】:

在 kotlin 中你可以添加这个函数来改变文本颜色:

private fun getActionText(@StringRes stringRes: Int, @ColorRes colorRes: Int): Spannable? {
            val spannable: Spannable = SpannableString(applicationContext.getText(stringRes))
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
                spannable.setSpan(
                    ForegroundColorSpan(applicationContext.getColor(colorRes)), 0, spannable.length, 0
                )
            }
            return spannable
        }

之后,您只需通过builder 调用它:

builder.addAction(R.drawable.ic_call_end, getActionText(R.string.reject,R.color.red), rejectPendingIntent)
builder.addAction(R.drawable.ic_accept, getActionText(R.string.accept,R.color.green), acceptPendingIntent)

您可以在通知中添加更多按钮。

【讨论】:

    【解决方案5】:

    要在文本中添加格式(粗体、斜体、换行符、颜色等),您可以添加styling with HTML markup

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多