Adding the DayNight theme to an app

suggest change

The DayNight theme gives an app the cool capability of switching color schemes based on the time of day and the device’s last known location.

Add the following to your styles.xml:

<style name="AppTheme" parent="Theme.AppCompat.DayNight">

@color/colorPrimary @color/colorPrimaryDark @color/colorAccent

</style>

The themes you can extend from to add day night theme switching capability are the following:

Apart from colorPrimary, colorPrimaryDark and colorAccent, you can also add any other colors that you would like to be switched, e.g. textColorPrimary or textColorSecondary. You can add your app’s custom colors to this style as well.

For theme switching to work, you need to define a default colors.xml in the res/values directory and another colors.xml in the res/values-night directory and define day/night colors appropriately.

To switch the theme, call the AppCompatDelegate.setDefaultNightMode(int) method from your Java code. (This will change the color scheme for the whole app, not just any one activity or fragment.) For example:

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

You can pass any of the following three according to your choice:

It is also possible to get the current night mode status using the getDefaultNightMode() method. For example:

int modeType = AppCompatDelegate.getDefaultNightMode();

Please note, however, that the theme switch will not persist if you kill the app and reopen it. If you do that, the theme will switch back to AppCompatDelegate.MODE_NIGHT_AUTO, which is the default value. If you want the theme switch to persist, make sure you store the value in shared preferences and load the stored value each time the app is opened after it has been destroyed.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents