使用不忽略夜间限定符的 ContextCompat 以编程方式从资源中获取颜色

Programmatically get color from resource using ContextCompat that doesn't ignore night qualifier

我目前正在使用 ContextCompat.getColor,但它没有获取正确的颜色。当应用程序遵守夜间资源限定符时,ContextCompat 从 values/colors.xml 而不是 values-night/colors.xml 获取颜色。

我试过这样的应用程序 使用一个主题,其中一个主题位于 values/styles.xmlvalues-night/styles.xml 但似乎颜色是使用资源文件夹预编译的,没有 -night 预选赛。

您可以自己查看主题是哪种模式:

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
}

来源:https://medium.com/@chrisbanes/appcompat-v23-2-daynight-d10f90c83e94#.l2fswuy4z