Home > Mobile >  Cant disable system's dark mode effect on my app- Android
Cant disable system's dark mode effect on my app- Android

Time:09-26

I am new to android and I am trying to disable system's dark mode affect on my app but cant achieve that anyway.Here's my theme.xml and its same in theme-night

<style name="Theme.MyAppName" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- Primary brand color. -->
    <item name="colorPrimary">@color/dark_red</item>
    <item name="colorPrimaryVariant">@color/dark_red</item>
    <item name="colorOnPrimary">@color/white</item>
    <!-- Secondary brand color. -->
    <item name="colorSecondary">@color/teal_200</item>
    <item name="colorSecondaryVariant">@color/teal_700</item>
    <item name="colorOnSecondary">@color/black</item>
    <!-- Status bar color. -->
    <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
    <!-- Customize your theme here. -->
    <item name="android:forceDarkAllowed" tools:targetApi="q">false</item>
</style>

I tried deleting the theme-night file. I have also tried this line juts below the onCreate AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); I also tried putting android:forceDarkAllowed=false in the layout of MainActivity. None of the solution worked for me. I am testing the app in Realme 2 Android 9. Please someone help me to achieve this.

CodePudding user response:

Extend your application class and call AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); in it's onCreate method. Like so:

public class App: Application() {
    override fun onCreate() {
        super.onCreate()
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
    }
}

Don't forget to register it in your manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yourpackage">

    <application
        android:name=".App" // <----- Your application class name
        // more stuff here >
    </application>
</manifest>

CodePudding user response:

Try this:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

or if have a button in project to turn on and off Dark Mode, could do this:

btn.setOnClickListener {
    if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
        // Turn off dark mode
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
    } else {
        // Turn on dark mode
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
    }
}
  • Related