Reputation: 123
I'm trying to implement an option to let the users specify if they want the app to load the theme based on the system settings (dark or light, i.e., if the device is set to use dark mode or not) but I what also to give the possibility to override the system settings.
I can easily find out how this setting is when launching the app for the first time, using something like the specified in this thread
However these seems to be useless after forcing the theme with:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
After changing the theme, I can't get the system setting anymore because it will always return "darkmode on", unless I force it again to light theme, but here again it will return "darkmode off" always! :(
Any idea, how to get the system setting?
Thanks in advance,
FF
Upvotes: 2
Views: 2894
Reputation: 2621
To detect if "system" is in dark mode or not, you can use getNightMode() method of UiModeManager class.
https://developer.android.com/reference/android/app/UiModeManager#getNightMode()
Like so,
UiModeManager uiModeManager = (UiModeManager) context.getSystemService(Context.UI_MODE_SERVICE);
int mode = uiModeManager.getNightMode();
if (mode == UiModeManager.MODE_NIGHT_YES) {
// System is in Night mode
} else if (mode == UiModeManager.MODE_NIGHT_NO) {
// System is in Day mode
}
And if want to know whether "your app" is in Night mode or not:
int mode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
switch (mode) {
case Configuration.UI_MODE_NIGHT_NO:
// App is in Day mode
break;
case Configuration.UI_MODE_NIGHT_YES:
// App is in Night mode
break;
case Configuration.UI_MODE_NIGHT_UNDEFINED:
// We don't know what mode we're in, assume notnight
break;
}
Upvotes: 6
Reputation: 123
Based on Kakyire's answer I figured out what the problem was.
I was assuming there was only two options to be passed to AppCompatDelegate.setDefaultNightMode, MODE_NIGHT_YES and MODE_NIGHT_NO but the thing is, I needed to pass MODE_NIGHT_FOLLOW_SYSTEM when "use system" is selected.
I hope this might be helpful to someone with the same "dificulty"
Happy coding,
FF
Upvotes: 1
Reputation: 122
After changing the theme, I can't get the system setting anymore because it will always return "darkmode on", unless I force it again to light theme, but here again it will return "darkmode off" always! :( Any idea, how to get the system setting?
In other to change the Theme
dynamically you need to use SharedPreferences
or Preference
for PreferenceScreen. This Github project can help you on how to implement Dark Theme
Upvotes: 1