首页 > 解决方案 > 当我更改暗模式时,如何重新创建活动?

问题描述

更改夜间模式时,我执行以下操作:

val nightMode = preferenceRepository.nightMode
preferenceRepository.nightMode = appContext.switchDarkLightMode(nightMode)

这是我的扩展:

fun Context.switchDarkLightMode(currentMode: Int): Int {
    val newMode = when (currentMode) {
        AppCompatDelegate.MODE_NIGHT_YES -> AppCompatDelegate.MODE_NIGHT_NO
        AppCompatDelegate.MODE_NIGHT_NO -> AppCompatDelegate.MODE_NIGHT_YES
        else -> {
            if (this.isDarkThemeSet()) AppCompatDelegate.MODE_NIGHT_NO
            else AppCompatDelegate.MODE_NIGHT_YES
        }
    }
    AppCompatDelegate.setDefaultNightMode(newMode)
    return newMode
}

据我所知:

setDefaultNightMode() 将自动将任何 DayNight 更改应用于任何“已启动”活动。这意味着您在调用 API 时不再需要手动重新创建任何活动。

:如何使用我需要的密钥重新创建活动,例如像这样:

fun restartLockableActivity() {
    startActivity(Intent(this, this.javaClass).apply { putExtra(KEY_SKIP_PIN, true) })
    finish()
}

更新:修改代码,但不起作用:

fun Context.switchDarkLightMode(currentMode: Int): Int {
    val newMode = when (currentMode) {
        AppCompatDelegate.MODE_NIGHT_YES -> AppCompatDelegate.MODE_NIGHT_NO
        AppCompatDelegate.MODE_NIGHT_NO -> AppCompatDelegate.MODE_NIGHT_YES
        else -> {
            if (this.isDarkThemeSet()) AppCompatDelegate.MODE_NIGHT_NO
            else AppCompatDelegate.MODE_NIGHT_YES
        }
    }
    AppCompatDelegate.setDefaultNightMode(newMode)
    val intent = Intent(this, this.javaClass).apply { putExtra(KEY_SKIP_PIN, true) }
    (this as? Activity)?.intent = intent
    return newMode
}

标签: androidkotlinandroid-activityandroid-night-mode

解决方案


您可以像这样使用recreate()

fun restartLockableActivity() {
    intent.putExtra(KEY_SKIP_PIN, true)
    recreate()
}

虽然让用户在操作系统设置中更改暗模式更容易,然后配置更改将负责重新创建您的应用程序。


推荐阅读