How to enable night mode programmatically?
SIMPLEST SOLUTION
You can enable/disable application's dark theme just by:
enable dark theme:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
forcefully disable dark theme:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
set app theme based on mobile settings of dark mode, i.e. if dark mode is enabled then the theme will be set to a dark theme, if not then
the default theme, but this will only work in version >= Android version Q (10)AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
Notes:
- Your base theme for app/activity should be
"Theme.AppCompat.DayNight"
like
<style name="DarkTheme" parent="Theme.AppCompat.DayNight">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
- Your res folder's names would end with -night so that different colors and images you can set for day and night themes like
drawable & drawable-night,
values & values-night
Can't disable Night Mode in my application even with values-night
I had the same issue on my Xiaomi Redmi Note 7. I tried this code inside MainActivity.create()
:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
But it doesn't work on some of Xiaomi devices including mine, though it works on other phones.
So the only solution I've found is to add <item name="android:forceDarkAllowed" tools:targetApi="q">false</item>
to each of your AppTheme
in styles.xml
. Like this:
<style name="MyTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:forceDarkAllowed" tools:targetApi="q">false</item>
</style>
It worked fine for my phone.
Enable android:forceDarkMode programmatically?
You can programmatically enable the dark theme on Android Q with the following code:AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
Related Topics
Gradle Project Sync Failing After Google Announced The New Sdk Versioning System
Putting Screen Densities into The Correct Bucket
Android Service Startservice() and Bindservice()
How to Remove White Underline in a Searchview Widget in Toolbar Android
How To: Install Plugin in Android Studio
Bitmapdrawable Deprecated Alternative
Change Background of Edittext's Error Message
Successful Share Intent for Android
Should I Use Getapplicationcontext or Activity.This in a Long Running Asynctask
Phone Number Validation Android
Error: Error Parsing Xml: Not Well-Formed (Invalid Token) ...
Ble Scan Is Not Working When Screen Is Off on Android 8.1.0
Supporting Amazon and Android Market (Google Play) Links Inside Application
How to Set Proxysettings and Proxyproperties on Android Wi-Fi Connection Using Java
Onoptionsitemselected Not Called When Using Actionlayout (Sherlockactionbar)
Failed to Find Build Tools Revision 21.1.1 - Sdk Up to Date
Creating Animation on Imageview While Changing Image Resource
How to Open The Avd Manager on Ubuntu Linux from The Command Line