如何检测手机系统是深色主题还是浅色主题?

时间:2021-01-27 03:31:21

标签: java android

这是我们使用应用程序时检测暗/亮主题的代码。

public void onConfigurationChanged(@NonNull Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    int mSysThemeConfig = newConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK;
    layout = findViewById(R.id.mainLayout);
    switch (mSysThemeConfig) {
        //Light theme
        case Configuration.UI_MODE_NIGHT_NO:
            layout.setBackgroundResource(R.drawable.lightTheme);
            layout.setLayoutParams(new RelativeLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            break;
        //Dark theme
        case Configuration.UI_MODE_NIGHT_YES:
            layout.setBackgroundResource(R.drawable.darkMode);
            layout.setLayoutParams(new RelativeLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            break;
    }
}

如何在启动应用程序时检测深色/浅色主题?

1 个答案:

答案 0 :(得分: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;
}

或者你可以进入这个链接

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