Android 当我更改黑暗模式时,如何使用extra重新创建活动?
更改夜间模式时,我会执行以下操作:Android 当我更改黑暗模式时,如何使用extra重新创建活动?,android,kotlin,android-activity,android-night-mode,Android,Kotlin,Android Activity,Android Night Mode,更改夜间模式时,我会执行以下操作: val nightMode = preferenceRepository.nightMode preferenceRepository.nightMode = appContext.switchDarkLightMode(nightMode) 这是我的分机: fun Context.switchDarkLightMode(currentMode: Int): Int { val newMode = when (currentMode) {
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()将自动将任何日夜更改应用于
任何“已开始”的活动。这意味着你不再需要
调用API时手动重新创建任何活动
Q:如何使用所需的密钥重新创建活动,例如:
fun restartLockableActivity() {
startActivity(Intent(this, this.javaClass).apply { putExtra(KEY_SKIP_PIN, true) })
finish()
}
fun restartLockableActivity() {
intent.putExtra(KEY_SKIP_PIN, true)
recreate()
}
更新:
修改了代码,但不起作用:
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
}
您可以这样使用:
fun restartLockableActivity() {
startActivity(Intent(this, this.javaClass).apply { putExtra(KEY_SKIP_PIN, true) })
finish()
}
fun restartLockableActivity() {
intent.putExtra(KEY_SKIP_PIN, true)
recreate()
}
尽管让用户在操作系统设置中更改暗模式更容易,然后配置更改将负责重新创建您的应用。当我调用
switchDarkLightMode
mode时,自动重新创建活动。方法restartLockableActivity
我举个例子。啊,我明白了,但是你可以只使用onSaveInstanceState(outState:Bundle)并在onCreate(savedInstanceState:Bundle?)中使用保存的状态而不是额外的状态,对吗?