无法在我的应用程序上禁用系统的暗模式效果 - 安卓



我是安卓系统的新手,我试图在我的应用程序上禁用系统的暗模式影响,但无论如何都无法实现。这是我的主题.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>

我尝试删除主题之夜文件。我还尝试过将这条线突出到onCreateAppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);下面。我还尝试将android:forceDarkAllowed=false放在MainActivity的布局中。所有的解决方案对我都不起作用。我正在Realme 2 Android 9中测试该应用程序。请有人帮我实现这一点。

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

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>

试试这个:

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

或者如果项目中有一个按钮来打开和关闭黑暗模式,可以这样做:

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

最新更新