android - 从最近的背景中删除应用程序后,应用程序中的暗模式未应用
问题描述
先看下面这张图
【白色模式1】https://i.stack.imgur.com/QKcju.jpg
【白色模式2】https://i.stack.imgur.com/QKcju.jpg
[黑暗模式1] https://i.stack.imgur.com/QKcju.jpg
[黑暗模式2] https://i.stack.imgur.com/QKcju.jpg
问题是->当我通过单击抽屉布局设置按钮打开黑暗活动并按下黑暗按钮后将黑暗模式应用于整个应用程序,当我从最近的背景中删除应用程序然后打开应用程序时,白色模式将自动应用于活动回家,但从抽屉布局再次打开暗活动后,它会自动应用暗模式。
这是我实现的代码
const val FIRST_START = "FirstStart"
const val NIGHT_MODE = "NightMode"
const val PREF = "AppSettingsPrefs"
class language_settings : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
loadLocate() // call LoadLocate
setContentView(R.layout.activity_language_settings)
//save preferences specific to an app, like save the dark mode again when we again
open the app
val appSettingsPrefs: SharedPreferences = getSharedPreferences(PREF, 0)
val isNightModeOn: Boolean = appSettingsPrefs.getBoolean(NIGHT_MODE, false)
val isFirstStart: Boolean = appSettingsPrefs.getBoolean(FIRST_START,false)
//Create a new Editor for these preferences through which you can make
modifications to
// the data in the preferences and atomically commit those changes back to the
SharedPreferences object
val editor: SharedPreferences.Editor = appSettingsPrefs.edit()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isFirstStart ){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
else{
when {
isNightModeOn -> {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}
else -> {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
}
}
btnSwitch.setOnClickListener {
if (isNightModeOn) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
editor.putBoolean(FIRST_START, false)
editor.putBoolean(NIGHT_MODE, false)
editor.apply()
recreate() //recreate activity to make changes visible, onPause, onStop,
onDestroy, endAllActiveAnimators, onStart, onResume
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
editor.putBoolean(FIRST_START, false)
editor.putBoolean(NIGHT_MODE, true)
editor.apply()
recreate() //recreate activity to make changes visible, onPause, onStop,
onDestroy, endAllActiveAnimators, onStart, onResume
}
}
please don't mind my english ;P
解决方案
你需要先AppCompatDelegate.setDefaultNightMode(mode)
打电话super.onCreate(savedInstanceState)
。
推荐阅读
- visual-studio - 能否使用 Visual Studio 重构 Azure SQL DataWarehouse 中的列名或表名?
- git - 在合并输出中显示提交之间的差异
- shell - 如何在另一台服务器上运行脚本
- python - Python:访问特定的子列表元素
- r - 将带有条件的自定义函数传递给 dplyr::mutate
- kubernetes - 如何在 RHEL 机器上的 Kubernetes 集群上识别 Kong 的 IP?
- python - 使用 extend() 时出现意外的“无”
- c++ - std::unordered_map 析构函数不释放内存?
- excel - wordpress首页中导出的excel表中包含的标题菜单
- c# - 忽略 asmx Web 服务中的参数