DayNight Theme in Android


In this tutorial, you will learn how to import and use DayNight Theme in your Android project.

 

Android DayNight Theme Example using AppCompat v23.2 support library provides simple solution for auto switching between Day and Night Theme. DayNight Theme choose Theme as per current time and last known location. This DayNight Theme works on API 14+ devices. Let’s explore Android DayNight Theme Tutorial step by step.

 

Getting Started

We need to set DayNight Theme in your style.xml file, you can use any of the following theme

Theme.AppCompat.DayNight
Theme.AppCompat.DayNight.NoActionBar
Theme.AppCompat.DayNight.DarkActionBar

 

Sample of DarkActionBar Theme:

Sometimes you need separate resources according night or day mode. For this you can use night resource qualifier to differentiate from default resources

for example

Drawable (for default mode)
Drawable-night (for night mode)

values (for default mode)
values-night (for night mode)

like this you can differentiate all resources if you need different view for night mode.

In this example, we will change background color and text color according mode type. So add colors to colors.xml file in values and values-night folder.

colors.xml file in values folder

colors.xml file in values-night folder

Put Main logic of setting Auto Switching DayNight Theme in MainActivity.java file

We can set default mode programmatically using setDefaultNightMode() method like bellow

For Setting Default Auto Switching Night Mode

For Setting Default Night Mode

For Setting Default Day Mode

ScreenShot:

daynight_day_theme.pngdaynight_night_theme.png

Complete Source code available here.


About Durga Chiranjeevi

I’m a normal guy, engineer by education who is passionate about Programming and Internet. An android enthusiast, now moving for cross platforms and game development.