代码之家  ›  专栏  ›  技术社区  ›  Cheok Yan Cheng

如何获取通知下拉式背景色,并在启用夜间模式时确定最佳文本颜色?

  •  3
  • Cheok Yan Cheng  · 技术社区  · 5 年前

    最近,当Android 9.0pie&Android操作系统的夜间模式启用时,我的用户向我发送了以下屏幕截图。

    enter image description here

    如您所见,股票名称不可见,因为股票名称应用黑色。在普通的白色主题中,它假定如下所示

    enter image description here


    这是我用来突出显示文本颜色的代码。在我的代码中,我总是假设下拉式通知的背景是白色的。(在启用暗模式时不正确)

    <?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;
    }
    

    我可以知道,如何获得通知下拉式背景色,并决定最佳文本颜色时,夜间模式启用?

    0 回复  |  直到 5 年前
        1
  •  0
  •   Md. Nowshad Hasan    5 年前

    我认为您可以使用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/值/主题.xml 文件-

    <style name="Theme.AppCompat.DayLight" 
           parent="Theme.AppCompat.Light" />
    

    还有另一个文件 res/values之夜/主题.xml -

    <style name="Theme.AppCompat.Night" 
           parent="Theme.AppCompat.DayNight" />
    

    你可以尝试不同的属性,比如 Theme.AppCompat 而不是 Theme.AppCompat.DayNight . 实际上,我没有运行此代码,但似乎只需稍加修改就可以工作。 请看一下安卓系统 documentation , this stackoverflow问题与此媒体 blog