android - 当我更改暗模式时,如何重新创建活动?
问题描述
更改夜间模式时,我执行以下操作:
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
}
解决方案
您可以像这样使用recreate():
fun restartLockableActivity() {
intent.putExtra(KEY_SKIP_PIN, true)
recreate()
}
虽然让用户在操作系统设置中更改暗模式更容易,然后配置更改将负责重新创建您的应用程序。
推荐阅读
- objective-c - ScriptingBridge - 它是如何“在幕后”工作的
- reactjs - 将 p5 包导入 React 功能组件?
- linux - 更改 Linux 内核模块引导顺序
- java - 替换弹簧配置文件特定属性文件中的属性占位符
- html - 行距不对齐
- excel - 如果选中该行中的复选框,我想锁定/保护该行中的特定范围的单元格
- java - 链接 JSON 文件和 java 文件
- python - Tkinter显示和隐藏窗口并恢复执行而不在python中破坏?
- c# - Linq 将 SQL 响应从一个类转换为按 .net 核心分组的嵌套类输出
- azure - 使用在 Azure 上运行的 Node.js Express 应用程序将 HTTP 流量重新路由到 HTTPS