You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过代码阻止小米设备强制应用深色模式?

解决小米设备强制覆盖应用深色主题的问题

对付小米设备强制生成深色主题、盖掉你自定义颜色的问题,试试这几个方案:

1. 直接禁用MIUI的深色主题强制适配

在AndroidManifest.xml的<application>标签里加个meta-data,明确告诉MIUI别强制应用深色模式:

<meta-data
    android:name="MIUISupportDarkMode"
    android:value="false" />

2. 主题里禁用系统强制深色转换

不管是用theme.kt还是styles.xml定义主题,都加上android:forceDarkAllowed属性设为false,阻止系统(包括MIUI)自动把浅色主题转深色:

// theme.kt示例
val LightTheme = theme(Theme.MaterialComponents.Light.NoActionBar) {
    // 你的浅色主题颜色配置
    ...
    androidAttributes {
        attribute(android.R.attr.forceDarkAllowed, false)
    }
}

val DarkTheme = theme(Theme.MaterialComponents.Dark.NoActionBar) {
    // 你的深色主题颜色配置
    ...
}

要是用XML写主题:

<style name="AppTheme.Light" parent="Theme.MaterialComponents.Light.NoActionBar">
    <!-- 其他配置项 -->
    <item name="android:forceDarkAllowed">false</item>
</style>

3. 动态切主题时明确指定模式

当应用自己有深色模式开关时,切换的时候用AppCompatDelegate.setDefaultNightMode()直接指定模式,别依赖系统的跟随逻辑,确保应用的主题设置优先级比厂商的强制设置高:

// 开启应用深色模式
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
// 开启应用浅色模式
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)

备用方案:反射关闭MIUI强制深色(针对旧版本)

如果上面的方法不管用,试试用反射怼MIUI的强制逻辑(兼容非MIUI设备,异常直接忽略就行):

fun disableMiuiForceDark() {
    try {
        val viewClazz = Class.forName("android.view.View")
        val forceDarkAutoField = viewClazz.getField("FORCE_DARK_AUTO")
        forceDarkAutoField.setAccessible(true)
        val forceDarkAuto = forceDarkAutoField.getInt(null)
        val setForceDarkAllowedMethod = viewClazz.getMethod("setForceDarkAllowed", Boolean::class.java)
        setForceDarkAllowedMethod.invoke(window.decorView, false)
        
        // 同时给Window也设置一下
        val windowField = window::class.java.getField("mForceDarkAllowed")
        windowField.setAccessible(true)
        windowField.set(window, false)
    } catch (e: Exception) {
        // 非MIUI设备或者反射失败就跳过
    }
}

在Activity的onCreate()里调用这个函数即可。

内容的提问来源于stack exchange,提问作者Juncu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 03:46:06