问题
I want to implement android 10 dark theme in my app , I have these following cases:
SYSTEM_DEFAULT, NIGHT_MODE, LIGHT_MODE
The problem is when I change theme from night or light to system_default from inside the app and it can not understand whether the system is in light mode or dark mode. so the theme won't be updated.
I've tried the dark theme by google https://developer.android.com/guide/topics/ui/look-and-feel/darktheme
and implementing the configuration still won't be good for me because I don't want to recreate my activity if user changes day to system default when system default is day.
Is there anyway I could handle this?
when(id) {
NIGHT - > theme = Theme.NIGHT_MODE
DAY - > theme = Theme.LIGHT_MODE
SYSTEM_DEFAULT - > theme = Theme.SYSTEM_DEFAULT
}
context ? .clearCachedDrawables()
activity ? .recreate()
}
EDIT:
when (themeStatus) {
Theme.LIGHT_MODE ->
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
Theme.NIGHT_MODE ->
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
Theme.SYSTEM_DEFAULT ->
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
回答1:
You don't need to set the theme in your activity and recreate it. It's done automatically if you've setup your app theme right.
To use the Dark in your app, you should extend the DayNight theme as your app theme.
<style name="AppTheme" parent="Theme.AppCompat.DayNight">
or
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
If you want for example a different color during dark mode, you should create a 'Android resource directory' called values-night with a 'resource file called colors.xml
In the colors.xml you can set a different color hex for one of your existing colors.
For example:
values/colors.xml contains
<color name="myColor">#000000</color>
values-night/colors.xml contains
<color name="myColor">#FFFFFF</color>
EDIT
You can switch between Dark/light mode in app by calling
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
or
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
or
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
来源:https://stackoverflow.com/questions/57955769/dark-theme-configuration-change-in-android-q