Android - 如何使用AppCompatDelegate.MODE_NIGHT_AUTO检测夜间模式是否打开

Ben*_*654 24 android android-night-mode

我正在使用Androids内置的日/夜模式功能,我想为我的应用添加一个选项 AppCompatDelegate.MODE_NIGHT_AUTO

我遇到了问题,因为我的应用程序需要以编程方式对某些内容进行着色,而我无法弄清楚如何检查应用程序是在夜间还是白天模式中考虑自己.没有它,我不能设置标志来选择正确的颜色.

调用AppCompatDelegate.getDefaultNightMode()只返回无用的AppCompatDelegate.MODE_NIGHT_AUTO.

我没有看到任何可以告诉我的东西,但一定有什么东西?

eph*_*ent 33

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;
}
Run Code Online (Sandbox Code Playgroud)

  • @ StarWind0我没有找到其他答案;这个答案完全来自API文档。 (2认同)

Mus*_*oya 18

要检查夜间模式,您可以执行以下操作:

public boolean isNightMode(Context context) {
    int nightModeFlags = context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
    return nightModeFlags == Configuration.UI_MODE_NIGHT_YES;
}
Run Code Online (Sandbox Code Playgroud)


Ali*_*Nem 8

Java 中的按位运算符(在 @ephemient 的答案中使用)在 kotlin 中是不同的,因此对于初学者来说,代码可能不容易转换。这是 kotlin 版本,以防万一有人需要它:

    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
    }
}
Run Code Online (Sandbox Code Playgroud)


jus*_*ser 8

一个非常简单的解决方案是像这样添加一个字符串资源。

res/values/strings.xml

<string name="mode">Day</string>
Run Code Online (Sandbox Code Playgroud)

res/values-night/strings.xml

<string name="mode">Night</string>
Run Code Online (Sandbox Code Playgroud)

然后在您需要检查的地方:

if (resources.getString(R.string.mode) == "Day") {
    // Do Day stuff here
} else {
    // Do night stuff here
}
Run Code Online (Sandbox Code Playgroud)

但是你不能super.onCreate()在活动的生命周期之前调用它。它总是会在 之前返回“Day” onCreate


abh*_*bhi 8

Kotlin 版本:->

fun isDarkMode(context: Context): Boolean {
    val darkModeFlag = context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
    return darkModeFlag == Configuration.UI_MODE_NIGHT_YES
}
Run Code Online (Sandbox Code Playgroud)


Sau*_*are 5

如果您是kotlin开发人员,则可以使用下面的代码来判断暗模式。

 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 -> {}
    }
Run Code Online (Sandbox Code Playgroud)

有关黑暗主题模式的更多信息

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

  • 你的时间并不详尽,否则对于金额不足的情况会更好 (5认同)