【发布时间】: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