We will not go into details of why we should be implementing night/dark mode. We shall straight dive into details of how to implement this.
Add a custom theme to styles.xml file.
Here the Base application theme is defined by default or is the old application theme that your app used earlier.
The Custom application theme is using Android’s default DayNight mode as parent and will help us in configuring the Dark/Night Mode.
Change theme parameter of each Activity in the Manifest file to AppTheme.DayNight.
We have now successfully added Night mode to our app. For the theme to take effect, we need to add the following lines to every Activity’s onResume function:
// for enabling night mode
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);// for disabling night mode
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);// for enabling night mode in auto mode
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);// for enabling night mode while following system settings
Changing Icons’ color with changing theme
There may be some icons which also need to change colors with the change in theme.
For this we will be using Vector Drawables.
Create a new vector drawable for the existing icon and add attribute android:fillColor as shown below.
Further we can also add a Toggle to change theme in the Settings of the App using SharedPreferences. An example is shown here.
Link to CryptoTrack : Playstore