Reputation: 4241
I implemented the dark theme using DayNight material themes in my app. I followed several articles and conference talks on the internet. Everything worked well until some small things started to occur. Let me explain:
The app has several activities. In order to not theme every activity explicitly, I followed advice to put the initial theme setting in my Application's onCreate() method. This has one drawback though, which I will explain next.
1.) AppCompat implements night mode at the activity level, which means that it won't update the application context (which I am using to set the theme app wide) (source: https://issuetracker.google.com/issues/134379747)
2.) The following piece of code is recommended to check whether or not the app is running in which mode. But it returns exactly the opposite mode in my case:
val currentNightMode = configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
when (currentNightMode) {
Configuration.UI_MODE_NIGHT_NO -> {} // Night mode is not active, we're using the light theme
Configuration.UI_MODE_NIGHT_YES -> {} // Night mode is active, we're using dark theme
}
3.) When setting my app to follow system and then I manually switch to light mode (in the app) and then come back to follow system, my app stays light even tho my phone is in system-wide dark theme. It does change however when toggling my app's theme.
What am I doing wrong? Could a possible solution be to set the theme on an activity level?
Upvotes: 3
Views: 2056
Reputation: 2146
when (resources.configuration.uiMode.and(Configuration.UI_MODE_NIGHT_MASK)) {
Configuration.UI_MODE_NIGHT_NO -> themeLight.isChecked = true
Configuration.UI_MODE_NIGHT_YES -> themeDark.isChecked = true
Configuration.UI_MODE_NIGHT_UNDEFINED -> themeLight.isChecked = true
}
use the above code to get the current theme. Inorder to change the theme instantly you need to add
AppCompatDelegate.setDefaultNightMode(themeMode)
Upvotes: 1
Reputation: 124
in your resources folder you can add a bools.xml in your value_night folder with below code
<resources>
<bool name="is_night_mode">true</bool>
</resources>
and in default folder make false
<resources>
<bool name="is_night_mode">false</bool>
</resources>
and in class file access it like Boolean isNightTheme = context.getResources().getBoolean(R.bool.preferences_autoplay);
Hope it helps.
Upvotes: 2