首页 > 解决方案 > 无法在我的应用程序上禁用系统的暗模式效果 - Android

问题描述

我是 android 新手,我正在尝试禁用系统的暗模式对我的应用程序的影响,但无论如何都无法实现。这是我的 theme.xml,在主题之夜中也是如此

<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>

我尝试删除主题之夜文件。我也试过这条线突出在 onCreate 下面我 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); 试过把. 没有一个解决方案对我有用。我正在 Realme 2 Android 9 中测试该应用程序。请有人帮助我实现这一目标。android:forceDarkAllowed=falseMainActivity

标签: androidandroid-layout

解决方案


扩展您的应用程序类并调用AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);它的onCreate方法。像这样:

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

不要忘记在清单中注册它:

<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>

推荐阅读