最近,当启用 Android 9.0 Pie 和 Android 操作系统的夜间模式时,我的用户向我发送了以下屏幕截图。
如您所见,股票名称是不可见的,因为股票名称应用了黑色。在普通的白色主题中,它应该如下所示
这是我用来突出文本颜色的代码。在我的代码中,我总是假设下拉通知的背景是白色的。 (在启用暗模式的情况下这是不正确的)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="NotificationTitle" parent="android:TextAppearance.Material.Notification.Title"></style>
</resources>
public SpannableString getFallBelowSpannableString(Context context) {
if (fallBelowSpannableString != null) {
return fallBelowSpannableString;
}
if (fallBelow == null) {
return null;
}
// The attributes you want retrieved
int[] attrs = {android.R.attr.textColor};
TypedArray ta = context.obtainStyledAttributes(R.style.NotificationTitle, attrs);
int textColor;
try {
textColor = ta.getColor(0, context.getResources().getColor(R.color.notification_symbol_name));
} finally {
ta.recycle();
}
final String notificationMessage = context.getString(R.string.falls_below_template, symbol, org.yccheok.jstock.watchlist.Utils.toStockPrice(fallBelow));
fallBelowSpannableString = new SpannableString(notificationMessage);
ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(textColor);
fallBelowSpannableString.setSpan(foregroundColorSpan, 0, symbol.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return fallBelowSpannableString;
}
我可以知道如何获取通知下拉背景颜色,并在启用夜间模式时确定最佳文本颜色吗?
最佳答案
我认为您可以使用 UiModeManager 类来获取当前模式。虽然不能确定用户在“自动”模式下是否处于暗模式。让我们看一下代码 -
UiModeManager uiModeManager = (UiModeManager) c.getSystemService(Context.UI_MODE_SERVICE);
int modeType = uiModeManager.getNightMode();
您还可以从下面的代码模式类型 -
int currentNightMode = getResources().getConfiguration().uiMode
& Configuration.UI_MODE_NIGHT_MASK;
switch (currentNightMode) {
case Configuration.UI_MODE_NIGHT_NO:
// Night mode is not active, we're in day time
case Configuration.UI_MODE_NIGHT_YES:
// Night mode is active, we're at night!
case Configuration.UI_MODE_NIGHT_UNDEFINED:
// We don't know what mode we're in, assume notnight
}
之后,您可以根据模式更改文本颜色。但我找到了另一种替代方法来完成您的工作。比如根据模式改变你的资源风格,比如在你的 res/values/themes.xml 文件中-
<style name="Theme.AppCompat.DayLight"
parent="Theme.AppCompat.Light" />
还有另一个文件res/values-night/themes.xml -
<style name="Theme.AppCompat.Night"
parent="Theme.AppCompat.DayNight" />
您可以尝试不同的属性,例如只使用 Theme.AppCompat
而不是 Theme.AppCompat.DayNight
。我实际上并没有运行这段代码,但似乎只做了一点点改动。
请看一下android documentation , this stackoverflow 问题和这个媒介 blog .
关于android - 如何获取通知下拉背景颜色,并在启用夜间模式时确定最佳文本颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55507712/