In this tutorial, we will discuss and learn, how to use DayNight theme of an Android in your Android Application to enable.
With the increasing usage of mobile devices, developers are constantly striving to improve user experience and provide innovative features.
A new theme has been added by Android to AppCompat Theme.AppCompat.DayNight with support library 23.2.0.
This enables the user to toggle switch between night mode and day mode. This feature can be very useful if you have a reading application in your android app, let start with implementing night mode in android.
Understanding the DayNight Functionality in AppCompat
To kick things off, you need to grasp the concept of the DayNight functionality in AppCompat. This feature is the key to enabling your app to alternate between the dark and light themes.
To activate it, you need to modify your theme to extend from one of the DayNight variants and then trigger the feature with a single method call. Here’s a sample theme declaration you can use:
<style name="MyTheme" parent="Theme.AppCompat.DayNight">
<!-- Additional settings -->
</style>
If you’re utilizing Material Design Components (which I highly recommend), you can also use the Theme.MaterialComponents.DayNight theme from their v1.1.0 release.
Benefits of implementing Day Night theme
Implementing the Day Night theme in Android applications offers several benefits.
Firstly, it enhances user experience by providing a visually pleasing interface that reduces eye strain during nighttime usage.
The dark theme also conserves battery life, especially on devices with OLED or AMOLED screens, as fewer pixels need to be illuminated.
Additionally, the Day Night theme gives users the flexibility to choose their preferred theme, providing a personalized experience.
Activating the Night Mode Feature
To turn on the feature in your app, you need to call the AppCompatDelegate.setDefaultNightMode() method, which accepts one of the following values:
- MODE_NIGHT_NO: Always employ the day (light) theme.
- MODE_NIGHT_YES: Always employ the night (dark) theme.
- MODE_NIGHT_FOLLOW_SYSTEM: This setting follows the system’s setting, which on Android Q and above is a system setting.
- MODE_NIGHT_AUTO_BATTERY: Switches to dark when the device has its ‘Battery Saver’ feature enabled, light otherwise.
- MODE_NIGHT_AUTO_TIME & MODE_NIGHT_AUTO: Toggles between day/night based on the time of day.
Note that this method is static, meaning you can call it at any time. However, the value you set doesn’t persist across process starts. Therefore, you need to set it every time your app process starts. The best way to do this is by setting it in your application class like so:
public class MyApplication extends Application {
public void onCreate() {
super.onCreate();
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_YES);
}
}
Overriding the Default Value
The setLocalNightMode() method allows you to override the default value in each component. This can be useful if only certain components should use the DayNight functionality or for development so you don’t have to wait for nightfall to test your layout.
However, using this method in every Activity is now considered an anti-pattern, and you should transition to using setDefaultNightMode() instead.
Activity Recreations
When using either setDefaultNightMode() or setLocalNightMode(), your Activity will be recreated if a Configuration change is necessary to apply the new theme. This is an excellent opportunity to test whether your Activity and Fragments save their instance state correctly.
Checking the Current Configuration
You can determine the current configuration by checking your resource configuration using the following code:
int currentNightMode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
switch (currentNightMode) {
case Configuration.UI_MODE_NIGHT_NO: // Night mode is not active, we're in day time
case Configuration.UI_MODE_NIGHT_YES: // Night mode is active, we're at night!
case Configuration.UI_MODE_NIGHT_UNDEFINED: // We don't know what mode we're in, assume notnight
}
Also Read: Google Login And Registration For Android Using Firebase Authentication
Follow the below steps to add this functionality in your Application:-
- ADD THEME Open styles.xml by app>res>values>styles.xmlAdd parent=“Theme.AppCompat.DayNight.DarkActionBar”
Styles.xml
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources>
2. Add Activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <Switch android:id="@+id/switch_toggle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="80dp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="DARKMODE TUTORIAL" android:layout_gravity="center" android:textSize="30dp" android:layout_marginTop="50dp"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="BUTTON" android:layout_marginTop="50dp"/> </LinearLayout>
3. Add MainActivity.java
package com.example.darkmode; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.app.AppCompatDelegate; import android.view.View; import android.widget.CompoundButton; import android.widget.Switch; import android.widget.Toast; import com.mahfa.dnswitch.DayNightSwitch; import com.mahfa.dnswitch.DayNightSwitchListener; public class MainActivity extends AppCompatActivity { Switch aSwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); aSwitch=findViewById(R.id.switch_toggle); aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { //if day mode is enabled, set night mode using AppCompatDelegate class. Toast.makeText(MainActivity.this, "Night selected", Toast.LENGTH_SHORT).show(); getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES); } else { //if night mode is enabled, set day mode using AppCompatDelegate class. Toast.makeText(MainActivity.this, "Day mode selected", Toast.LENGTH_SHORT).show(); getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO); } } }); } }
Now, you are ready to run your application.
When you will run, you can see your application like this:-
Impact on battery life
One of the significant advantages of the Day Night theme is its positive impact on battery life. As mentioned earlier, dark themes consume less power on devices with OLED or AMOLED screens. The reduced power consumption can result in extended battery life, allowing users to enjoy their applications for a more extended period without needing to recharge their devices frequently.
System Night Mode
Android Q and later versions have a system night mode that can be enabled in the Settings app. Android Pie also has a system night mode setting, but it’s only accessible in the device’s ‘developer options’. For simplicity, I recommend treating Android Pie the same as previous Android versions.
In-app Setting
It’s recommended to provide a method for the user to override the default theme in your app. The recommended options and strings are:
- ‘Light’ (MODE_NIGHT_NO)
- ‘Dark’ (MODE_NIGHT_YES)
- ‘Set by Battery Saver’ (MODE_NIGHT_AUTO_BATTERY). Only show on Android Pie and below. This should be your app’s default when shown.
- ‘Use system default’ (MODE_NIGHT_FOLLOW_SYSTEM). Only show on Android Q and above. This should be your app’s default when shown.
A common way to implement this would be via a ListPreference, calling to setDefaultNightMode() when the value changes.
Updating Your Themes and Styles
In addition to calling AppCompat, you will likely need to update your themes, styles, and layouts so that they work seamlessly across both dark and light themes. Here are some important theme attributes to know about:
- ?android:attr/textColorPrimary: General-purpose text color. Will be near-black on light theme, near-white on dark themes. Contains a disabled state.
- ?attr/colorControlNormal: General-purpose icon color. Contains a disabled state.
Using Material Design Components makes this much easier, as its attributes (such as ?attr/colorSurface and ?attr/colorOnSurface) provide an easy generalized themed color to use. These attributes can, of course, be customized in your theme.
Challenges in implementing the Day Night theme
While the Day Night theme offers numerous benefits, there are certain challenges associated with its implementation. Developers need to ensure that all elements of the application, including third-party libraries and custom views, are compatible with the day and night themes. In some cases, certain UI components may require additional customization to maintain consistency across different themes.
You can also access code through our following GitHub link:-
Hope you like this Article. Stay tuned for more such android related Articles.
For any Query, Comment down Below!!!!!