最近,启用Android 9.0 Pie和Android OS的夜间模式后,我的用户向我发送了以下屏幕截图。
如您所见,股票名称不可见,因为股票名称使用了黑色。在正常的白色主题中,它看起来如下
这是我的代码用来突出显示文本颜色。在我的代码中,我始终假定下拉通知的背景是白色。(如果启用了暗模式,那是不正确的)
<?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;
}
Run Code Online (Sandbox Code Playgroud)
我可以知道,当启用夜间模式时,如何获取通知下拉背景颜色并确定最佳文本颜色?
我认为您可以使用 UiModeManager 类来获取当前模式。尽管无法确定用户在“自动”模式下是否处于黑暗模式。让我们看一下代码 -
UiModeManager uiModeManager = (UiModeManager) c.getSystemService(Context.UI_MODE_SERVICE);
int modeType = uiModeManager.getNightMode();
Run Code Online (Sandbox Code Playgroud)
您还可以从下面的代码中进行模式输入 -
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
}
Run Code Online (Sandbox Code Playgroud)
之后,您可以根据模式更改文本颜色。但我找到了另一种替代方法来完成你的工作。就像根据模式更改资源样式一样,例如在res/values/themes.xml文件中 -
<style name="Theme.AppCompat.DayLight"
parent="Theme.AppCompat.Light" />
Run Code Online (Sandbox Code Playgroud)
另一个文件res/values-night/themes.xml -
<style name="Theme.AppCompat.Night"
parent="Theme.AppCompat.DayNight" />
Run Code Online (Sandbox Code Playgroud)
您可以尝试不同的属性,例如使用 only Theme.AppCompat而不是Theme.AppCompat.DayNight。实际上我没有运行这段代码,但似乎只需进行一些更改即可工作。请查看 android文档、stackoverflow问题和媒体博客。
| 归档时间: |
|
| 查看次数: |
236 次 |
| 最近记录: |