【问题标题】:How to recreate activity with extra when i change dark mode?当我更改暗模式时,如何重新创建活动?
【发布时间】:2020-06-15 09:54:41
【问题描述】:

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

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
}

【问题讨论】:

    标签: android kotlin android-activity android-night-mode


    【解决方案1】:

    你可以像这样使用recreate()

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

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

    【讨论】:

    • 当我调用switchDarkLightMode 模式时会自动重新创建活动。方法restartLockableActivity我举个例子。
    • 啊,我明白了,但是您可以使用 onSaveInstanceState(outState: Bundle) 并在 onCreate(savedInstanceState: Bundle?) 中使用保存状态而不是你的附加值,对吧?
    猜你喜欢
    • 1970-01-01
    • 2021-04-28
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    相关资源
    最近更新 更多