I am facing an issue with the theme application in my Android app.
Problem:
When the app is freshly installed and the user logs in for the first time:
The device theme is set to dark
The users' preferred app theme (from API response) is light
The app ends up applying the theme twice, which causes the UI to reload or flicker (appears like the screen is redrawn or shown on top of itself).
Theme application logic:
when (response.displayMode) {
"light" -> {
setTheme(AppCompatDelegate.MODE_NIGHT_NO)
sharedPreferences.edit().putInt("theme_mode", AppCompatDelegate.MODE_NIGHT_NO).apply()
viewModel.setLightTheme(true)
}
"dark" -> {
setTheme(AppCompatDelegate.MODE_NIGHT_YES)
sharedPreferences.edit().putInt("theme_mode", AppCompatDelegate.MODE_NIGHT_YES).apply()
viewModel.setDarkTheme(true)
}
"auto" -> {
setTheme(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
sharedPreferences.edit().putInt("theme_mode", AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM).apply()
viewModel.setAutoTheme(true)
}
}
private fun setTheme(mode: Int) {
AppCompatDelegate.setDefaultNightMode(mode)
}
I am calling this code in onCreate() of either the Activity or a Fragment (tried both).
I also tried setting android:launchMode="singleInstance" and singleTask, which prevents the screen from visibly duplicating, but internally the theme is still applied again.
Questions:
How can I prevent the theme from being applied twice or reinitializing the UI unnecessarily?
What's the best place/time to apply the theme correctly after login based on the user's preferences?
-
show your whole onCreatetyczj– tyczj2025年07月29日 15:29:12 +00:00Commented Jul 29, 2025 at 15:29