问题
Since Android 10, you can switch between dark mode and default light mode. I didn't make any closer research yet on this since it's a new topic. Is Dark mode color switching automatic by OS or is there any way to tell my App to switch different app-theme if Dark mode is turned on? Also dark mode is possibility for some Android 9 devices.
Because I made custom Dark theme with custom parameters and I set dark color for each of my color in resources (using custom attributes in attrs.xml
and applied specific color resource to them inside theme in styles.xml
). Same it is working for different color schemes of my App (blue, red, green for example). That way I can tell which color would be used for different views in my App and not system.
Only thing I need is to detect if dark mode is on/off in system. I can force user to turn on Dark mode in App settings (custom settings) but theme can be affected by system dark mode (turned on in Phone settings).
回答1:
From official documentations:
In order to support Dark theme, you must set your app's theme (usually found in res/values/styles.xml) to inherit from a DayNight theme:
<style name="AppTheme" parent="Theme.AppCompat.DayNight">
You can also use MaterialComponents' dark theming:
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
This ties the app's main theme to the system-controlled night mode flags and gives the app a default Dark theme (when it is enabled).
It means that if you use a DayNight theme, the OS itself handles the app theme. if you want to force app uses dark theme check this documentation.
UPDATE:
To detect the device theme:
switch (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) {
case Configuration.UI_MODE_NIGHT_YES:
…
break;
case Configuration.UI_MODE_NIGHT_NO:
…
break;
}
来源:https://stackoverflow.com/questions/59279914/android-how-to-switch-theme-for-dark-mode