Android - How to detect if night mode is on when using AppCompatDelegate.MODE_NIGHT_AUTO

不羁岁月 提交于 2019-11-27 20:57:39

问题


I'm using Androids built in day/night mode functionality and I'd like to add an option to my app for AppCompatDelegate.MODE_NIGHT_AUTO

I'm having a problem though because my app requires certain things to be colored programmatically, and I can't figure out how to check if the app considers itself in night or day mode. Without that, I can't set a flag to choose the right colors.

Calling AppCompatDelegate.getDefaultNightMode() just returns AppCompatDelegate.MODE_NIGHT_AUTO which is useless.

I don't see anything else that would tell me, but there must be something?


回答1:


int nightModeFlags =
    getContext().getResources().getConfiguration().uiMode &
    Configuration.UI_MODE_NIGHT_MASK;
switch (nightModeFlags) {
    case Configuration.UI_MODE_NIGHT_YES:
         doStuff();
         break;

    case Configuration.UI_MODE_NIGHT_NO:
         doStuff();
         break;

    case Configuration.UI_MODE_NIGHT_UNDEFINED:
         doStuff();
         break;
}



回答2:


If you are kotlin developer then you can use below code to judge dark mode.

 val mode = context?.resources?.configuration?.uiMode?.and(Configuration.UI_MODE_NIGHT_MASK)
    when (mode) {
        Configuration.UI_MODE_NIGHT_YES -> {}
        Configuration.UI_MODE_NIGHT_NO -> {}
        Configuration.UI_MODE_NIGHT_UNDEFINED -> {}
    }

For more about dark theme mode

https://github.com/googlesamples/android-DarkTheme/




回答3:


The bitwise operator in Java (which is used in @ephemient 's answer) is different in kotlin so the code might not be easily convertible for beginners. Here is the kotlin version just in case someone needs it:

    private fun isUsingNightModeResources(): Boolean {
        return when (resources.configuration.uiMode and 
Configuration.UI_MODE_NIGHT_MASK) {
            Configuration.UI_MODE_NIGHT_YES -> true
            Configuration.UI_MODE_NIGHT_NO -> false
            Configuration.UI_MODE_NIGHT_UNDEFINED -> false
            else -> false
    }
}


来源:https://stackoverflow.com/questions/44170028/android-how-to-detect-if-night-mode-is-on-when-using-appcompatdelegate-mode-ni

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!