I created my application before the android pie has been released, in every layout I put android: background = \"white\"
it works fine in every device, but when
In themes.xml change:
<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
to
<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light.DarkActionBar">
in layout of your activity that you want to disable force dark, place following attribute in parent layout:
android:forceDarkAllowed="false"
your layout should be like this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
android:forceDarkAllowed="false">
<!-- ..... -->
</androidx.constraintlayout.widget.ConstraintLayout>
Tested using Xiaomi Note 8 Pro MIUI 12.0.2 Android 10
Adding AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
to MainActivity.onCreate();
doesn't seems to be working
The working solution was to add <item name="android:forceDarkAllowed">false</item>
inside our main AppTheme
block in styles.xml
Example:
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="android:forceDarkAllowed" tools:targetApi="q">false</item>
</style>
If you want to avoid Activity recreations you could set the flag on the Application class as mentioned here
I recommend setting it in your application class (if you have one) like so:
public class MyApplication extends Application {
public void onCreate() {
super.onCreate();
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
use this as parent for disable dark mode parent="Theme.AppCompat.Light.NoActionBar
What suggested by Ali Rezaiyan is the correct way to proceed if you want disable the night mode all over your app.
Sometimes you just need to disable the night mode on some activities or fragment only (maybe because of legacy stuff).
So you can choose what to do:
Disable all over the app:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
Disable for a single Activity:
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
- After calling this you probably need to call
recreate()
for this to take effect