6

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).

martin1337
  • 1,450
  • 2
  • 18
  • 55
  • 3
    have you looked at [this](https://stackoverflow.com/questions/59134005/how-to-automatically-switch-to-dark-mode-on-android-app/59134396#59134396) – a_local_nobody Dec 11 '19 at 08:02

1 Answers1

9

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; 
}
Ali Sadeghi
  • 328
  • 3
  • 16
  • Will try this. Because as I mentioned, if I have 5 different color variations of my App, I have to make 5 different dark themes for them. That means I have to pick which color theme based on which light theme is currently used by App. – martin1337 Dec 11 '19 at 06:55
  • @martin1337 Check the updated answer. You can detect device theme and base on that, set your app theme. – Ali Sadeghi Dec 11 '19 at 06:58
  • It is working fine with `and` operator instead of & inside when(). And I also tested it on Android 10 virtual device. I should call this code in onResume I suppose, because my theme did not switched only after app restart. – martin1337 Dec 11 '19 at 08:03
  • 1
    @martin1337 No. you need to set night mode in application class. Check a_local_nobody comment on the question. – Ali Sadeghi Dec 11 '19 at 09:36