I've implemented a Dark / night mode switch in my App I copied the implementation from the Google I/O App.
I've created a ThemedActivityDelegate that can be included in ViewModels. The actual changing to light or dark is done using the Extension function: updateForTheme
.
But I see the SettingsActivity
briefly flashing white before it turns black. While I put the updateForTheme
method before setContentView
.
MainActivity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
viewModel = ViewModelProvider(this, viewModelFactory).get(MainViewModel::class.java)
updateForTheme(viewModel.currentTheme)
lifecycleScope.launch {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
launch {
viewModel.theme.collect { theme ->
updateForTheme(theme)
}
}
}
}
}
Extensions.kt:
fun AppCompatActivity.updateForTheme(theme: Theme) = when (theme) {
Theme.DARK -> delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_YES
Theme.LIGHT -> delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_NO
Theme.SYSTEM -> delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
Theme.BATTERY_SAVER -> delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY
}
SettingsActivity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
updateForTheme(Theme.DARK)
setContentView(R.layout.activity_settings)
}
from Activity quickly flashes white before switching to dark / night theme
No comments:
Post a Comment